Jquery.ajax不会像对GET数据那样自动为您编码POST数据。jQuery希望您的数据经过预格式化,以附加到请求正文中,以直接通过网络发送。
一种解决方案是使用jQuery.param函数来构建查询字符串,大多数处理POST请求的脚本都希望使用该字符串。
$.ajax({
url: 'superman',
type: 'POST',
data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
在这种情况下,该param方法会将数据格式化为:
field1=hello&field2=hello2
该Jquery.ajax文档中说,有一个叫标志processData控制该编码是否是自动还是没有这样做。该文档说它默认为true,但这不是我在POST使用时观察到的行为。