2014-10-30 95 views
0

我有一个问题集成ajax调用与node.js(我使用express.js)。 这是我的代码:Ajax调用和node.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调用不工作,我有什么是结果的白色页面我查询,例如: { biglietto:2.70 }

回答

0

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

问题是,当你激发提交事件时,除了你在提交处理程序中放置的内容之外,还会出现一大堆默认行为,例如重新绘制整个页面的结果请求(你不想要的)。

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

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

然后您可以继续处理其余的代码。

+0

如果我编写event.preventDefault(),ajax调用可以工作,但服务器不发送任何东西。我不明白为什么= \ – simonav 2014-10-31 16:55:10