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

标签 jquery ajax curl basic-authentication

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

我错过了什么?

最佳答案

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

关于jquery - 将curl命令转换为jQuery $.ajax(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20155531/

相关文章:

使用 orderByChild 和 equalTo 来冰壶 Firebase?

php - 尝试使用 Adaptive Simple Payments 但出现黑屏

javascript - curl 到 JavaScript

javascript - 如何使用 Tampermonkey 脚本替换 AJAX 驱动的页面文本和选择属性中的大量单词?

javascript - 单击 <a> 链接时如何关闭导航栏?

javascript - 仅在蒙版图像上显示图标

javascript - Grid.MVC 禁用嵌入按钮的 onrowselect

javascript - JQuery $.getJSON() 不适用于回调

在 Bootstrap Modal 中使用 django 清晰表单的 AJAX 反馈表单

javascript - 无法迭代对象数组(未定义错误)