我想用js发送post消息给服务器,并且要求返回json格式的数据,我查了一下jquery的文档,但是还是没办法把accept=json加入到header中。代码如下
function getCode(param, config, notice){
var url = config.apiBase
+ "/resource/";
var data = {
"name": param.name,
"user_agent": param.ua,
"mobile": $("#phone").val()
};
$.post(url, data, )
.done(function(data){
console.log(data);
if(data.ret){
notice.showMsg({
msg: "短信验证码已经发送。",
type: "info",
deley: 0,
duration: 0,
close: true
});
countDown();
}else{
notice.showMsg({
msg: "短信验证码发送失败。",
type: "error",
deley: 0,
duration: 0,
close: true
});
}
})
$.post()
不支持加入headers
信息,改用$.ajax()
。demo 如下:http://api.jquery.com/jQuery.ajax/
看文档,
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 is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.
这一段的介绍,可以在配置参数中,修改传输的格式,默认是 'application/x-www-form-urlencoded; charset=UTF-8'。