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

时间:2013-11-22 22:16:56

标签: jquery ajax curl basic-authentication

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

我错过了什么?

1 个答案:

答案 0 :(得分:26)

默认情况下,$ .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");
    }
});