Ajax call and node.js

Ajax call and node.js

本文关键字:js node and call Ajax      更新时间:2023-09-26

我在将ajax调用与node.js集成时遇到问题(我使用的是express.js)。这是我的代码:

Page.html

<div id = "prezzo" class="col-md-12" style = "display : none">
      <div class="col-md-2 col-md-offset-3">
        <h1 id = "h1">€ </h1>
      </div>
      <div class="col-md-4">
        <input style="margin-top: 17px" type="submit" class="btn btn-sommatinese btn-lg btn-block" />
      </div>
    </div>
    </div>
<script type = "text/javascript">
$("#form1").submit(function()
            {
              $("#prezzo").fadeIn(600, function()
                {
                  $.ajax({
                    url: "http://localhost:3000/prezzo",
                    type: "GET",
                    success: function(data)
                    {
                      console.log(data);
                      $("#h1").append(data.biglietto);
                    }
                  });
                });
            });
</script>

Page.js

exports.prezzo = function(req,res) {
req.getConnection(function(err,connection) {
    connection.query("my query", function(err,rows) {
      if(err) console.log("Error selecting : %s", err);
      if(rows.length > 0) {
          totale = rows[0];
          res.send(totale);
          //console.log(totale);
        }
    });
});
}

ajax调用不起作用,我得到的是一个白色页面,上面有我的查询结果,如下所示:{比格利托:2.70}

我在HTML中看不到#form1,但无论如何。。。

问题是,当您触发提交事件时,除了您在提交处理程序中放入的内容外,还会发生一系列默认行为,例如用请求的结果重新绘制整个页面(这是您不想要的)。

您需要做的是防止默认行为,以便您的事件处理程序是提交时唯一发生的事情。提交处理程序的前两行应该是这样的:

$("#form1").submit(function(event){
    event.preventDefault();

然后,您可以继续执行代码的其余部分。