闽公网安备 35020302035485号
// 以下是未配置`contentType`前的layui表格代码:
var Monthly = table.render({
elem: '#table', // 堆代码 duidaima.com
url: "../url", //数据接口
method: "post",
where: {pageSize: 10, pageIndex: 0},
height: "full-100",
even: true, //开启隔行背景
cols: [[ //表头
{ field: 'time', title: '时间'}
]],
});
// 在这段代码中,没有设置`contentType`,所以如果后端要求JSON格式的数据,这个请求会失败。为了确保后端能正确处理请求,可以设置`contentType`为`application/json`,如下所示:
var tableReturn = table.render({
elem: '#table',
url: "../url", //数据接口
method: "post",
where: {pageSize: 10, pageIndex: 0},
contentType: 'application/json', // 请求数据类型
height: "full-100",
even: true, //开启隔行背景
cols: [[ //表头
{ field: 'time', title: '时间'}
]],
});
类似的情况在使用$.ajax进行请求时也常见。通常,jQuery的$.ajax默认的contentType是application/x-www-form-urlencoded,但在发送JSON数据时,需要显式将参数对象用JSON.stringify序列化,并设置contentType为application/json。
// 以下是未经修改的`$.ajax`请求代码:
$.ajax({
url: "../url",
type: "post",
data: {
PageIndex: 0,
PageSize: 10
},
success: function (res) {
}
})
// 在这种配置下,参数以表单格式发送,如果后端期待JSON格式的数据,可能会导致解析错误。因此,使用`JSON.stringify`序列化参数,并配置正确的`contentType`:
$.ajax({
url: "../url",
type: "post",
data: JSON.stringify({
PageIndex: 0,
PageSize: 10
}),
contentType: 'application/json', // 请求数据类型
dataType: 'json', // 响应数据类型
success: function (res) {
}
})
总结
在ajax 请求时 contentType 类型 默认为 application/x-www-form-urlencoded 即是 表单的格式,可以通过以上方式配置contentType 设置 数据格式方便前后端联调数据,以完成各种功能集合,即应用。此修改后,前端发送的请求数据将符合后端期望的JSON格式,使得请求能够顺利到达并被正确解析。