将curl cmd转换为jQuery $ .ajax()

我正在尝试使用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"); } });