将 curl cmd 转换为 jQuery $.ajax()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20155531/
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
Converting curl cmd to jQuery $.ajax()
提问by krisrak
I'm trying to make a api call with jquery ajax, I have curl working for the api, but my ajax is throwing HTTP 500
我正在尝试使用 jquery ajax 进行 api 调用,我有 curl 为 api 工作,但我的 ajax 正在抛出 HTTP 500
I have a curl command working that looks like this:
我有一个 curl 命令,看起来像这样:
curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api
I tried ajax like this, but it is not working:
我试过这样的ajax,但它不起作用:
$.ajax({
url: "http://www.example.com/api",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {foo:"bar"},
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
What am I missing ?
我错过了什么?
回答by krisrak
By default $.ajax() will convert data
to a query string, if not already a string, since data
here is an object, change the data
to a string and then set processData: false
, so that it is not converted to query string.
默认情况下 $.ajax() 将转换data
为查询字符串,如果还不是字符串,因为data
这里是一个对象,将 更改data
为字符串然后设置processData: false
,这样它就不会转换为查询字符串。
$.ajax({
url: "http://www.example.com/api",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: '{"foo":"bar"}',
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});