用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);
}
});
3 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
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字符串,JSON字符串是本机并内置到现代浏览器中的。如果您想支持旧的浏览器,您可能需要包括 控件指定请求内容类型。 contentType属性,以便向服务器指示发送JSON请求的意图。 这个 dataType: 'json'属性用于您希望从服务器获得的响应类型。jQuery足够聪明 猜
它来自服务器 Content-Type响应头。因此,如果您有一个Web服务器,它或多或少地尊重HTTP协议,并使用 Content-Type: application/json对于您的请求,jQuery将自动将响应解析为javascript对象到 success回调,这样您就不需要指定 dataType财产。
你所说的 arr是 不是数组
..它是一个具有属性的javascript对象( City和 Age)。数组用 []在javascript里。例如 [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]是一个由两个对象组成的数组。
噜噜哒
TA贡献1784条经验 获得超7个赞
$.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);});- 3 回答
- 0 关注
- 1606 浏览
添加回答
举报
0/150
提交
取消
