簡體   English   中英

如何在不重新加載或重新呈現頁面的情況下將node.js后端的JSON返回到前端?

[英]How can I return JSON from node.js backend to frontend without reloading or re-rendering the page?

我正在使用node.js.

我想按下一個搜索按鈕,對后端的另一台服務器進行一些休息api調用,然后將json返回到前端,並在前端重新加載一個div,這樣我就不必刷新頁面了。 現在我知道我可以用jQuery或只是Javascript dom操作重新加載一個div。

但是如何讓它在服務器端調用方法呢? 我可以有一個提交按鈕,它會發出一個帖子請求,我可以抓住它並從那里進行api調用,但是從node.js那邊,當我返回時,我將不得不再次渲染頁面。 如何在不重新渲染或刷新頁面的情況下將JSON從后端返回到前端?

謝謝。

以下演示了如何制作基本的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);
    }); 
});

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>

總結評論(遺憾的是,問題沒有被正確地問到):你想要的是對不同域上的服務器進行AJAX調用,然后是JavaScript。 通常,由於相同的原始政策,您不能這樣做。 然而有一些黑客:

1)使用jQuery的AJAX和dataType: 'jsonp' 您應該閱讀並了解有關JSONP的更多信息。

2)對您的域進行AJAX調用,讓服務器調用另一台服務器。 使用Node.JS,您可以使用:

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

請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM