2017-08-20 42 views
0

我對ajax/node/jquery非常陌生,所以請原諒任何菜鳥錯誤。ajax和jquery,可以發送數據到服務器但不能收到它

我想發送數據到節點服務器和更新頁面的響應使用jQuery,我可以發送數據到服務器,但無法得到響應。 我相信成功的方法不會解僱,因爲我從來沒有收到警報。

所以,我的目的是點擊size_button,將size_form的內容發送到服務器。完成的項目將處理size_form的內容,但對於此示例,只需將其發送回服務器並更新response即可。

jQuery代碼:

$(document).ready(function() { 

$('#size_button').click(function(e){ 
$('#response').html("searching for size..."); 
var url = "http://localhost:8081/search_size"; // the script where you handle the form input. 
$.ajax({ 
     type: "POST", 
     crossDomain: true, 
     url: url, 
     data: $("#size_form").serialize(), // serializes the form's elements. 
     //data: $('#size_form'); 
     success: function(data) 
     { 
      alert(data); // show response from the php script. 
     $('#response').html(data); 
     } 
    }); 
e.preventDefault(); // avoid to execute the actual submit of the form. 

}); 
}); 

的Node.js代碼:

var express = require('express'); 
var app = express(); 
var bodyParser = require('body-parser'); 

// Create application/x-www-form-urlencoded parser 
var urlencodedParser = bodyParser.urlencoded({ extended: false }) 

app.post('/search_size', urlencodedParser, function(req, res) { 
    response = {batch_size: req.body.batch_size}; 
if(req.body.batch_size){ 
    var size = req.body.batch_size; 
    console.log('looking for batches with ' +size+ ' items'); 
    res.end(JSON.stringify(response)); 
    } else { 
    console.log('recieved request for 0 items'); 
    } 

    //res.end('request recieved...'); 
    res.end(JSON.stringify(response)); 
}); 

var server = app.listen(8081, "localhost", function() { 
var host = server.address().address 
var port = server.address().port 
console.log("Server listening at http://%s:%s", host, port) 

}) 

HTML代碼:

<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> 
<script src="jquery.js"></script> 
</head> 
<body>  
    <form action='' method='POST' id='size_form'> 
    <p>search for size</p> 
    <input type='text' name="batch_size" id='batchsize'/> 
    <input type='submit' value='Submit'id='size_button' method='POST'/> 
    </form> 
    <div id='response'></div> 
    </body> 
</html> 
+0

當您調試時,它在哪裏/如何失敗?在瀏覽器的調試工具中,控制檯上是否有錯誤? JavaScript代碼是否按預期執行?是否發起AJAX呼叫?它是否包含您期望的數據?服務器的迴應是什麼? – David

+0

@David除了'跨源請求被阻止:訪問控制 - 允許 - 來源'丟失'問題,一切看起來都很棒,這是什麼令我困惑。我收到了'在服務器中尋找55個項目 '的批次,並在頁面中搜索大小...,所以我知道jquery按鈕點擊正在工作。正如我之前所說的,我非常確定'成功'沒有發射,因爲我從來沒有'alert(data)';' – JONAS402

+0

由於同源策略,瀏覽器的聲音阻止了請求(https://en.wikipedia.org/wiki /同樣 - origin_policy)。使用Google錯誤信息返回許多有用的結果,包括各種堆棧溢出問題。 – David

回答

0

因此,原來的伎倆是CORS或跨源資源共享,我設法通過安裝和使用Cors模塊來解決我的問題。

npm install cors --save

Server.js代碼:

導入模塊:

var cors = require('cors')

使用該模塊與服務器應用程序變量:

app.use(cors())

獲取更多信息: www.npmjs.com/package/cors

相關問題