javascript 使用ajax请求传递js对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24691312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass js object with ajax request
提问by Cereal Killer
I need to send a js object to the server through ajax request; is an object containing parameters for a sql query with Sequelize orm in node js; an example is like this:
我需要通过ajax请求向服务器发送一个js对象;是一个包含节点 js 中带有 Sequelize orm 的 sql 查询参数的对象;一个例子是这样的:
var data =
{
include: [
{ model: model.Shop },
{ model: model.Product,
include: [
{ model: model.File }
]
}
]
}
It can contain arrays of objects nested on multiple levels; before sending it I can convert it to valid JSON if needed, like this:
它可以包含嵌套在多个级别上的对象数组;在发送之前,如果需要,我可以将其转换为有效的 JSON,如下所示:
var data =
{
"include": [
{ "model": "model.Shop" },
{ "model": "model.Product",
"include": [
{ "model": "model.File" }
]
}
]
}
I've tried to send it as JSON:
我尝试将其作为 JSON 发送:
$.ajax({
//...
data: data
});
The problem is that when in the node server I do JSON.parse of the received string, the value of each property is a string and it is not recognized as a model object;
问题是,当我在节点服务器中对接收到的字符串做 JSON.parse 时,每个属性的值都是一个字符串,并且不被识别为模型对象;
How can I make my server able to understand this?
我怎样才能让我的服务器能够理解这一点?
回答by Nikhil Talreja
回答by Mritunjay
Don't put manually quotes to your data object.
不要手动引用您的数据对象。
try
尝试
JSON.stringify(data)
It will convert that to acceptable string format.
它会将其转换为可接受的字符串格式。