我正在尝试使用jquery ajax进行api调用,我让curl为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");
}
});
我错过了什么?
发布于 2013-11-24 04:58:31
默认情况下,$.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");
}
});
https://stackoverflow.com/questions/20155531
复制