AJAX的 contentType
contentType默认
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
一、 简单的JSON
var p = {name : 'luo', score : '100'};
$.ajax({
type: "post",
url: "/role/contentTypeTest",
dataType: 'json',
data: p,
error: function(request) {
layer.alert('添加失败');
},
success: function(result) {
layer.msg('保存成功');
}
});
二、复杂的 JSON对像
var p = {
name: 'yuwen',
score: [
{'luo' : '100'},
{'lei' : '98'}
]
};
$.ajax({
type: "post",
url: "/role/contentTypeTest",
dataType: 'json',
data: p,
error: function(request) {
layer.alert('添加失败');
},
success: function(result) {
layer.msg('保存成功');
}
});
这个复杂对象, application/x-www-form-urlencoded 这种形式是没有办法将复杂的 JSON 组织成键值对形式。你传进去之后可以发送请求,但是服务端收到数据为空, 因为 ajax不知道怎样处理这个数据。
HTTP还可以自定义数据类型,于是就定义一种叫 application/json 的类型。我们 ajax 的复杂JSON数据,用 JSON.stringify序列化后然后发送,在服务器端接到然后用 JSON.parse 进行还原就行了。
var p = {
name: 'yuwen',
score: [
{'luo' : '100'},
{'lei' : '98'}
]
};
$.ajax({
type: "post",
url: "/role/contentTypeTest",
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: JSON.stringify(p),
error: function(request) {
layer.alert('添加失败');
},
success: function(result) {
layer.msg('保存成功');
}
});