我正在尝试使用jquery ajax进行api调用,我正在为该API工作,但是我的ajax抛出了HTTP 500
我有一个curl命令,看起来像这样:
curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api
我像这样尝试过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");
}
});
我想念什么?
默认情况下,$。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");
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句