如何在不重新加载或重新呈现页面的情况下将node.js后端的JSON返回到前端?

时间:2012-06-26 20:51:44

标签: javascript jquery node.js dom post

我正在使用node.js。

我想按一个搜索按钮,对后端的另一台服务器进行一些休息api调用,然后将json返回到前端,并在前端重新加载一个div,这样我就不必刷新了页。现在我知道我可以用jQuery或只是Javascript dom操作重新加载一个div。

但是如何让它在服务器端调用方法呢?我可以有一个提交按钮,它会发出一个帖子请求,我可以抓住它并从那里进行api调用,但是从node.js那边,当我返回时,我将不得不再次渲染页面。如何在不重新渲染或刷新页面的情况下将JSON从后端返回到前端?

感谢。

3 个答案:

答案 0 :(得分:6)

以下演示了如何制作基本的AJAX请求。

小提琴:http://jsfiddle.net/tWdhy/1/

$(function(){
    $.ajax({
        url: '/echo/json/', //the URL to your node.js server that has data
        dataType: 'json',
        cache: false
    }).done(function(data){
        //"data" will be JSON. Do what you want with it. 
        alert(data);
    }); 
});

    

答案 1 :(得分:5)

http://expressjs.com/

在服务器上大致相似:

var app = express.createServer();
app.use(express.bodyParser());
app.post('/search', function(req, res){
   search_form = req.body;  // <-- search items
   MySearch.doSearch(search_form,function(err,items) {
       res.send(items);
   });
});

app.listen(3000);

您必须实施doSearch代码才能返回您正在搜索的内容....

客户端:

   <script>
   $.ajax( {
      url: '/search',
      data: search_form,
      type: 'POST',
      success: function(items) {
          /* do something with items here */
          // You will likely want a template so you don't have to format the string by hand
        for( var item in items ) {
           $('#results').append('<div>'+item.interestingField+'</div>);
        }
      }
   });
   </script>

答案 2 :(得分:1)

总结评论(遗憾的是,问题没有得到正确解答):你想要的是对服务器进行AJAX调用,该服务器位于不同的域,然后是JavaScript。通常,由于相同的原始政策,您不能这样做。然而有一些黑客:

1)将jQuery的AJAX与dataType: 'jsonp'一起使用。您应该阅读并了解有关JSONP的更多信息。

2)对您的域进行AJAX调用,让服务器调用另一台服务器。使用Node.JS,您可以使用:

var http = require('http');
http.request(/* options */);

请参阅the documentation