我对ajax / node / jquery非常陌生,所以请原谅任何菜鸟错误。
我尝试将数据发送到节点服务器并使用jquery使用响应更新页面,我可以将数据发送到服务器但无法获得响应。 我确信成功方法没有解雇,因为我从未收到警报。
所以,我的目标是点击plt.bar(range(len(Points)),Points)
plt.xticks(range(len(Points)), Points.index)
,size_button
的内容被发送到服务器。完成的项目将处理size_form
的内容,但是对于此示例,只需发送回服务器并且需要更新size_form
。
Jquery代码:
response
Node.js代码:
$(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.
});
});
HTML code:
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)
})
答案 0 :(得分:0)
所以事实证明这个技巧是CORS或Cross Origin资源共享,我设法通过安装和使用cors模块解决了我的问题。
npm install cors --save
Server.js代码:
导入模块:
var cors = require('cors')
将模块与服务器app变量一起使用:
app.use(cors())
了解更多信息: www.npmjs.com/package/cors
答案 1 :(得分:0)
您使用的是错误的响应功能。你想要response.send()或response.json()。见http://expressjs.com/en/api.html#res.end