在使用 jQuery 的 $.ajax 方法进行 HTTP 请求时,contentType 参数用于指定发送到服务器的数据的编码类型。常见的 contentType 设置包括 'application/json' 和 'application/x-www-form-urlencoded; charset=UTF-8'。以下是对这两种 contentType 的详细对比和说明:
1. contentType: 'application/json'
用途:
• 用于发送 JSON 格式的数据。
特点:
• 数据格式:发送的数据是纯 JSON 字符串。
• HTTP 头部:Content-Type 被设置为 'application/json',告知服务器请求体的格式为 JSON。
• 适用场景:适用于需要传输复杂数据结构(如嵌套对象、数组等)的场景,通常与 RESTful API 一起使用。
示例代码:
```javascript
$.ajax({
url: '/login',
type: 'POST',
data: JSON.stringify({
username:"Lily",
password:"123456"}),
contentType: 'application/json',
dataType: 'json',
success: ...
})
服务器端处理:
• 服务器需要能够解析 JSON 格式的数据。例如,在servlet 中使用 fastjson进行解析:
@WebServlet

1万+

被折叠的 条评论
为什么被折叠?



