简体   繁体   English

Ajax调用和node.js

[英]Ajax call and node.js

I have a problem integrating ajax calls with node.js (I am using express.js). 我在将Ajax调用与node.js集成时遇到问题(我正在使用express.js)。 This is my code: 这是我的代码:

Page.html 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 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);
        }

    });
});
}

The ajax call doesn't work, what I have is a white page with the result of my query, like this: { biglietto: 2.70 } ajax调用不起作用,我的查询结果是白页,例如:{biglietto:2.70}

I can't see #form1 in your HTML, but anyway ... 我在您的HTML中看不到#form1 ,但是无论如何...

The problem is that when you fire a submit event, a whole bunch of default behavior occurs in addition to what you put in your submit handler, such as repainting the whole page with the results of the request (which you don't want). 问题在于,当您触发一个Submit事件时,除了您在Submit处理程序中放置的内容外,还会发生一堆默认行为,例如用请求的结果(您不想要的)重新绘制整个页面。

What you need to do is prevent the default behavior, so that your event handler is the only thing that happens on submit. 您需要做的是防止默认行为,以便事件处理程序是提交时发生的唯一事情。 The first two lines of your submit handler should look like this: 提交处理程序的前两行应如下所示:

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

Then you can continue on with the rest of your code. 然后,您可以继续其余的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM