jquery 在发布请求中设置标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19592577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery set header in post request
提问by Mattia Lipreri
I need to simulate this curl command
我需要模拟这个 curl 命令
curl -i -H "Accept: application/json" -H "Content-type:application/json" -X POST -d '{"username":"pippo","password":"secret123"}' http://url.org/api/login
via jquery, I made in this way
通过jquery,我是这样制作的
$( document ).ready(function() {
$.ajax({
url:"http://urlapi/user/login",
type:"POST",
headers: {
"Accept" : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
data:{ username: "pippo", password: "secret123" },
dataType:"json"
})
});
I still have has content-type text/html. Is it right?
我还有内容类型的 text/html。这样对吗?
回答by Polaris878
It appears to be working for me... Are you sure you are looking at the correct request? Take a look at the HTTP request in the following JSFiddle; it indeed contains the Content-Type
header:
http://jsfiddle.net/KqGY4/1/
它似乎对我有用...您确定您正在查看正确的请求吗?看看下面JSFiddle中的HTTP请求;它确实包含Content-Type
标题:http:
//jsfiddle.net/KqGY4/1/
$( document ).ready(function() {
$.ajax({
url:"http://fiddle.jshell.net/user/login",
type:"POST",
headers: {
"Accept" : "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
data:{ username: "pippo", password: "secret123" },
dataType:"json"
})
});
回答by electroid
Try beforeSend in your jQuery AJAX call:
在 jQuery AJAX 调用中尝试 beforeSend:
$( document ).ready(function() {
$.ajax({
url:"http://urlapi/user/login",
type:"POST",
beforeSend: function(xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
data:{ username: "pippo", password: "secret123" },
dataType:"json"
})
});
回答by Maulik Gangani
if you still want to use .post() -> call this function before it
如果你仍然想使用 .post() -> 在它之前调用这个函数
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
all jquery request after it will have these headers in it.
之后的所有 jquery 请求都将包含这些标头。
回答by denolk
have you tried contentType option?
您是否尝试过 contentType 选项?
$( document ).ready(function() {
$.ajax({
url:"http://urlapi/user/login",
type:"POST",
headers: {
"Accept" : "application/json; charset=utf-8"
},
contentType:"application/json; charset=utf-8",
data:{ username: "pippo", password: "secret123" },
dataType:"json"
})
});