使用 jQuery 发送 JSON 数据

为什么下面的代码以 City=Moscow&Age=25而不是 JSON 格式发送数据?

var arr = {City:'Moscow', Age:25};
$.ajax(
{
url: "Ajax.ashx",
type: "POST",
data: arr,
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
}
);
151095 次浏览

因为您既没有指定请求内容类型,也没有指定正确的 JSON 请求。以下是发送 JSON 请求的正确方法:

var arr = { City: 'Moscow', Age: 25 };
$.ajax({
url: 'Ajax.ashx',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function(msg) {
alert(msg);
}
});

注意事项:

  • 使用 JSON.stringify方法将 javascript 对象转换为 JSON 字符串,该字符串是原生的并内置于现代浏览器中。如果你想支持旧的浏览器,你可能需要包括 Json2.js
  • Specifying the request content type using the contentType property in order to indicate to the server the intent of sending a JSON request
  • dataType: 'json'属性用于您期望从服务器获得的响应类型。JQuery 具有足够的智能,可以从服务器 Content-Type响应头中对其进行 guess。因此,如果你有一个或多或少遵守 HTTP 协议并用 Content-Type: application/json响应请求的 Web 服务器,jQuery 会自动将响应解析成一个 javascript 对象,然后进入 success回调,这样你就不需要指定 dataType属性。

Things to be careful about:

  • 你所谓的 arr就是 不是数组。它是一个具有属性(CityAge)的 javascript 对象。数组用 javascript 中的 []表示。例如,[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]是一个由2个对象组成的数组。

因为默认情况下 jQuery 序列化作为 data参数传递给 $.ajax的对象。它使用 $.param将数据转换为查询字符串。

来自 $.ajax的 jQuery 文档:

[ data参数]转换为查询字符串(如果还没有字符串的话)

如果要发送 JSON,必须自己对其进行编码:

data: JSON.stringify(arr);

Note that JSON.stringify is only present in modern browsers. For legacy support, look into Json2.js

它被序列化,这样默认情况下 URI 可以读取 POST 请求中的名称值对。您可以尝试将 processData: false 设置为参数列表。不知道能不能帮上忙。

您需要设置正确的内容类型并将对象字符串化。

var arr = {City:'Moscow', Age:25};
$.ajax({
url: "Ajax.ashx",
type: "POST",
data: JSON.stringify(arr),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert(msg);
}
});

I wrote a short convenience function for posting JSON.

$.postJSON = function(url, data, success, args) {
args = $.extend({
url: url,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
success: success
}, args);
return $.ajax(args);
};


$.postJSON('test/url', data, function(result) {
console.log('result', result);
});