What is content-type and datatype in an AJAX request?
https://api.jquery.com/jquery.ajax/
What is content-type and datatype in an AJAX request?
contentType
is the type of data you're sending, so application/json; charset=utf-8
is a common one, as is application/x-www-form-urlencoded; charset=UTF-8
, which is the default.
dataType
is what you're expecting back from the server: json
, html
, text
, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify
the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
$.ajax - dataType
contentType
is the header sent to the server, specifying a particular format.- Example: I'm sending json or XML
dataType
is you telling jQuery what kind of response to expect.- Expecting JSON, or XML, or HTML, etc....the default it for jQuery to try and figure it out.
The $.ajax()
documentation has full descriptions of these as well.
In your particular case, the first is asking for the response to be in utf-8
, the second doesn't care. Also the first is treating the response as a javascript object, the second is going to treat it as a string.
So the first would be:
success: function(data) {
//get data, e.g. data.title;
}
The second:
success: function(data) {
alert("Here's lots of data, just a string: " + data);
}
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-10-10 “There's no Qt version assigned to this project for platform ” - visual studio plugin for Qt
2017-10-10 net user