[英]Cant get jquery AJAX to work node js express
I've been trying to get ajax to work on node js. 我一直在尝试让ajax在Node js上工作。 Its the first time working with ajax so i have been trying to test it out useing the console to check that it works but every time i try i don't get a response on the console.
它是第一次使用ajax,因此我一直在尝试使用控制台对其进行测试以检查其是否正常工作,但是每次尝试时,控制台上都没有响应。
Here is my code. 这是我的代码。
<script>
function getMessage() {
var data = $("#messageselect").val()
$.ajax({
url: "/message",
type: "POST",
data: JSON.stringify(data)
dataType: 'json',
success: function(data) {
console.log(data);
}
error : function(err)
console.log("error fetching message");
});
}
</script>
server 服务器
app.post('/message', function(req, res) {
console.log(JSON.stringify(req.body));
Message.findOne({ 'page.message' : req.data }, function(err, message) {
if(err)
throw err;
res.send(message);
});
});
html html
<form method="POST">
<select multiple="multiple" class="messageselect" onchange="getMessage()" id="messageselect">
<% if(message) { %>
<% for(i=messagecount-1;i>=0;i--) { %>
<option value="<%= message[i].page.message %>">From: <%= message[i].page.username %> Message: <%= message[i].page.messagetitle %></option>
<% } %>
<% } %>
</select><br><br><br>
</form>
I guess this is one of the typos error in your code: 我猜这是您的代码中的错别字之一:
var = data $("#messageselect").val()
//--^^--------------------------------worng way to assign.
jQuery.ajax()
needs an object to send: jQuery.ajax()
需要一个对象来发送:
var data = { data : $("#messageselect").val() };
and at the server you can use req.body
to get the posted data: 在服务器上,您可以使用
req.body
获取发布的数据:
console.log(req.body.data);
Note: 注意:
For this you need to have body-parser
for it, so make sure to include it in the code configs above. 为此,您需要具有
body-parser
,因此请确保将其包含在上面的代码配置中。
Could you please try $http
like below format , 您能否尝试使用
$http
这样的格式,
$http.post(//url , //data )
.success (function() {})
.error(function() {});
$.ajax({
url: "/message",
type: "POST",
data: JSON.stringify(data)
dataType: 'json',
success: function(data) {
console.log(data);
}
error : function(err)
console.log("error fetching message");
});
They are missing braces at the error handler 他们在错误处理程序中缺少括号
error : function(err) {
console.log("error fetching message");
}
Maybe not the right way so you also can try : 也许不是正确的方法,所以您也可以尝试:
$.ajax({
url: '/message',
type: 'POST',
dataType: 'JSON',
data: {JSON.stringify(data)},
success: function(data) {
console.log(data);
}
error : function(err) {
console.log("error fetching message");
}
});
Have you ever tried using curl
to POST something on server ? 您是否尝试过使用
curl
在服务器上发布内容?
In addition to existing answers you should also pass the proper Content-Type
with your AJAX request: 除了现有的答案,您还应该在AJAX请求中传递正确的
Content-Type
:
$.ajax({
url: "/message",
type: "POST",
data: JSON.stringify(data)
dataType: 'json',
contentType: 'application/json' //here it is
//...
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.