将 curl 命令转换为 jQuery $.ajax()

20

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

我错过了什么?


3
除非API支持CORS进行跨域请求,否则无法实现!但是您可以使用AJAX调用服务器端,然后让服务器执行cURL相关操作。 - adeneo
@adeneo 我正在使用自定义打包,不会阻止跨域请求,假设这是同一来源,请问我该如何让它工作? - krisrak
1个回答

39

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

2
谢谢,这回答了我的问题,在这里 http://stackoverflow.com/questions/30992688/creating-task-using-wunderlist-api/31015511#31015511 - damuz91

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接