Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:
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);
}
});
注意事项:
- Usage of the
JSON.stringify
method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include 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足够智能,可以从ServerContent-Type
响应头中删除它.因此,如果您有一个或多或少遵守HTTP协议的web服务器,并以Content-Type: application/json
响应您的请求,jQuery将自动将响应解析为success
回调中的javascript对象,这样您就不需要指定dataType
属性.
注意事项:
- 你所说的
arr
是not an array.它是一个具有属性(City
和Age
)的javascript对象.数组在javascript中用[]
表示.例如,[{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]
是2个对象的array.