为什么在下面的代码中将数据发送为City=Moscow&Age=25JSON格式而不是?
City=Moscow&Age=25
var arr = {City:'Moscow', Age:25}; $.ajax( { url: "Ajax.ashx", type: "POST", data: arr, dataType: 'json', async: false, success: function(msg) { alert(msg); } } );
因为您既未指定请求内容类型,也未指定正确的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
contentType
dataType: 'json'
Content-Type
Content-Type: application/json
success
dataType
arr
City
Age
[]
[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]