通过 jQuery 将 JavaScript 对象发送到 Web 服务器调用 - 正确的方法是什么?
我正在尝试通过 jQuery 将 JSON 数据发送到我的 Web 服务器,但遇到了错误。 未捕获的类型错误:无法使用“in”运算符在
我正在测试的{“id”:45,“isRead”:true}代码中搜索“上下文”:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
是否有更好或更正确的方法来执行此操作?也不确定 $.ajax 调用中的参数是否正确。
更新
我开始工作的代码
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
我的服务器期望 JSON 数据作为 application/json 发布。那么我认为我需要所有这些变量是错误的吗?如果没有这些,它会作为 GET 发送,并被 application/x-www-form-urlencoded 编码。没有 stringify 它也不起作用。
I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您向 ajax 函数传递了太多参数: http://api.jquery.com/jQuery.ajax /
此外,
JSON.stringify
调用不是必需的,jQuery 会为您处理这个问题。You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the
JSON.stringify
call is not necessary, jQuery will take care of that for you.您需要发送一个对象作为第二个参数
{success: success, data: data}
You need to send an object as second param
{success: success, data: data}
文档在这里:
http://api.jquery.com/jQuery.ajax/
你有将参数作为一个对象而不是多个对象传递
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones