【问题标题】:Unable to pass values back to HTML page无法将值传回 HTML 页面
【发布时间】:2016-07-04 16:25:45
【问题描述】:

我正在使用EJS 向我的页面发送一些值。以下是代码。

app.post('/ttt', function (req,res){
   res.render('index.ejs', {titles: 'CAME IN'})
});

HTML

<form id="mc-form" action="http://local_host:8081/ttt" method="post" enctype="multipart/form-data">
    <input type="email" value="" name="dEmail" class="email" id="mc-email" placeholder="type email &amp; hit enter" required=""> 
    <input type="submit" name="subscribe" >
    <label>REEEEE <%= titles %></label>
</form>

JS

<script type="text/javascript">
$("#mc-form").submit(function(e) {
    // e.preventDefault(); // Prevents the page from refreshing
    var $this = $(this); // `this` refers to the current form element
    $.post(
        $this.attr("action"), // Gets the URL to sent the post to
        $this.serialize(), // Serializes form data in standard format
        function(data) { /** code to handle response **/ 
            alert( data);
        },
        "json" // The format the response should be in
    );
});

但是,在用户单击提交按钮后,文本 CAME IN 不会显示在表单上。我该如何排序?

【问题讨论】:

  • 您没有将数据(html)附加到页面
  • 我该怎么做。我是初学者

标签: javascript jquery html node.js


【解决方案1】:

为ajax返回一个json而不是一个视图

node.js

app.post('/ttt', function (req,res){
   res.setHeader('Content-Type', 'application/json');
   res.send(JSON.stringify({titles: 'CAME IN'}));

}); 

plain.js

$("#mc-form").submit(function(e) {
    e.preventDefault(); // Prevents the page from refreshing
    var $this = $(this); // `this` refers to the current form element
    $.post(
        $this.attr("action"), // Gets the URL to sent the post to
        $this.serialize(), // Serializes form data in standard format
        function(data) { /** code to handle response **/
            $this.find('label').text(data.titles);//append the title to the form
        },
        "json" // The format the response should be in
    );
});

【讨论】:

  • 标签还没更新?我错过了身份证吗?还是?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2014-11-20
  • 1970-01-01
  • 2019-09-03
  • 1970-01-01
相关资源
最近更新 更多