我对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>
当您调试时,它在哪里/如何失败?在浏览器的调试工具中,控制台上是否有错误? JavaScript代码是否按预期执行?是否发起AJAX呼叫?它是否包含您期望的数据?服务器的回应是什么? – David
@David除了'跨源请求被阻止:访问控制 - 允许 - 来源'丢失'问题,一切看起来都很棒,这是什么令我困惑。我收到了'在服务器中寻找55个项目 '的批次,并在页面中搜索大小...,所以我知道jquery按钮点击正在工作。正如我之前所说的,我非常确定'成功'没有发射,因为我从来没有'alert(data)';' – JONAS402
由于同源策略,浏览器的声音阻止了请求(https://en.wikipedia.org/wiki /同样 - origin_policy)。使用Google错误信息返回许多有用的结果,包括各种堆栈溢出问题。 – David