转换卷曲cmd以jQuery的$。阿贾克斯() [英] Converting curl cmd to jQuery $.ajax()

查看:242
本文介绍了转换卷曲cmd以jQuery的$。阿贾克斯()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图与jQuery的AJAX一个API调用,我有卷曲工作的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

我想阿贾克斯这样的,但它不工作:

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

我在想什么?

What am I missing ?

推荐答案

在默认情况下$。阿贾克斯()将数据已经是一个字符串转换成一个查询字符串,如果不,因为数据这里是一个对象,改变数据为一个字符串,然后设置过程数据:假,系统使得它不转换为查询字符串。

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

这篇关于转换卷曲cmd以jQuery的$。阿贾克斯()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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