我有以下 JS 对象:
json =
{
"category_id": category,
"subcategory_id": subcategory,
"offer_type": type_offer,
"features": []
};
我尝试将此对象作为 JSON 发送,如下所示:
$.ajax({
type: 'POST',
url: '/add',
data: json,
success: function (data) {
},
contentType: "application/json",
dataType: 'json'
});
是吗?或者我需要提前做一些准备?
现在我使用这部分代码:
formObj = $("#form_add").serialize();
var json = {};
var wrapperObj = {json: json, form: formObj};
$.ajax({
type: 'POST',
url: '/add',
data: JSON.stringify(wrapperObj),
success: function (data) {
// TODO
},
contentType: "application/json",
dataType: 'json'
});
这个方法对吗?当我将两个对象打包在一个对象中并在 stringify
之后?
最佳答案
您需要使用 JSON.stringify 使其成为有效的 json
$.ajax({
type: 'POST',
url: '/add',
data: JSON.stringify(json),
success: function (data) {
},
contentType: "application/json",
dataType: 'json'
});
关于javascript - 如何将 JS 对象作为 JSON 正确发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47742092/