文章内容

2021/9/8 18:00:50,作 者: 黄兵

contentType 与 dataType 区别

最近在使用 Jquery 的 $.ajax() 向后端提交数据,具体代码片段如下:

$.ajax({
type: "POST",
url: "/api/v1/tools/ip-convert",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({"ip": $IPVal}),
beforeSend: function (xhr, settings) {
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrfToken)
}
},
success: function (data) {

这里使用了 contentType 和 dataType,两者有什么区别呢?

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
Type: String
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

向服务器发送数据时,请使用此内容类型。默认为“application/x-www-form-urlencoded; charset=UTF-8”,这在大多数情况下都适用。如果您显式地将内容类型传递给 $.ajax(),那么它将始终发送到服务器(即使没有发送数据)。如果没有指定字符集,数据将使用服务器的默认字符集传输到服务器;您必须在服务器端对其进行适当的解码。

dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

您期望从服务器返回的数据类型。如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它(XML MIME 类型将产生 XML,在 1.4 中 JSON 将产生一个 JavaScript 对象,在 1.4 脚本中将执行脚本,其他任何类型都将以字符串形式返回)。

也就是说:contentType 是你向服务器发送的数据类型,而 dataType 是接收的数据类型,两个正好相反。


参考资料:

1、jQuery.ajax()

2、Differences between contentType and dataType in jQuery ajax function

分享到:

发表评论

评论列表