无法将值传递回HTML页面

时间:2016-07-04 06:56:18

标签: javascript jquery html node.js

我正在使用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未显示在表单上。我该如何排序?

1 个答案:

答案 0 :(得分:3)

返回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
    );
});