这两天碰到ajax请求传递json对象,json对象里面包含list对象,到mvc后台就是绑定不到list对象,搞了半天就是不正确,后来一看同事没有调用自己写的代码,以为就是调用自己的代码呢,名字起的一样,却把我的方法拷贝过去,害的我找了半天,坑死人不偿命,下面记录一下,以免今后自己时间长忘了,这次也以为代码一样,也是时间长忘了,ajax请求的特殊配置,下面是json对象准备代码
var previewImgList = [];
//获取图集列表的数量,这里加5因为前面其他类型的图片默认已有五张
var imgListLength = 8;
for (var i = 0; i <= 8; i++) {
var imgInfo = new Object();
imgInfo["ImageUrl"] = i;
imgInfo["ImageDescription"] = i;
previewImgList.push(imgInfo);
}
var data = {
"UpLoadFile": "testUpLoadFile",
"Title": "testTitle",
"NewsContent": "testNewsContent",
"NewsSourceCode": "testNewsSourceCode",
"NewsSourceName": "testNewsSourceName",
"NewsLanguage": "testNewsLanguage",
"contentHtml": "testcontentHtml",
"Author": "testAuthor",
"operateType": "testoperateType",
"Id": "test",
"GenerateType": "0",
"PreviewType": "5",
"ImageList": previewImgList
};
//生成预览文件url地址
var generateUrl = "/NewsContent/PreviewProcess";
//0为生成预览文件,1为保存生成文件
AjaxRequest(generateUrl, ShowPreviewFile, "POST", data);
下面的代码是AjaxRequest方法
function AjaxRequest(reqUrl, func, reqType, reqData) {
console.log(reqUrl);
$.ajax({
type: reqType,
url: reqUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(reqData),
success: function (data) {
if (func != "")
func(data);
},
error: function (XMLHttpRequest, txtStatus, errorThrown) {
console.log(XMLHttpRequest.status);
console.log(txtStatus);
}
})
}
这里面特别注意不光要指定ajax请求的dataType为json,还要指定ContentType为application/json,然后data进行json转成字符串,不然后台会接收不到list对象