将 curl cmd 转换为 jQuery $.ajax() [英] Converting curl cmd to jQuery $.ajax()

查看:34
本文介绍了将 curl cmd 转换为 jQuery $.ajax()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jquery ajax 进行 api 调用,我有 curl 为 api 工作,但我的 ajax 抛出 HTTP 500

I'm trying to make a api call with jquery ajax, I have curl working for the api, but my ajax is throwing HTTP 500

我有一个如下所示的 curl 命令:

I have a curl command working that looks like this:

curl -u "username:password" -H "Content-Type: application/json" -H "Accept: application/json" -d '{"foo":"bar"}' http://www.example.com/api

我尝试过这样的ajax,但它不起作用:

I tried ajax like this, but it is not working:

$.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,这样就不会转换成查询字符串了.

By default $.ajax() will convert data to a query string, if not already a string, since data here is an object, change the data to a string and then set processData: false, so that it is not converted to query string.

$.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");
    }
});

这篇关于将 curl cmd 转换为 jQuery $.ajax()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆