如何将此curl转换为jQuery AJAX POST?

时间:2016-06-08 08:05:11

标签: javascript jquery ajax curl

curl --request POST \
--url 'https://usX.api.mailchimp.com/3.0/lists/1234/members' \
--user 'username:api_key' \
--header 'content-type: application/json' \
--data '{"email_address":"user@example.com", "status":"pending"}' \
--include

我在卷曲之上,当我尝试将订阅者添加到我的Mailchimp列表时,它正常工作。

但是,我不知道如何将此curl转换为工作jQuery AJAX POST请求,因为我只知道如何将data传递给AJAX POST。

由于此卷曲有--user--header--include,因此我不知道如何构建正确的AJAX。

请帮忙。

$.ajax({
    url : "https://usX.api.mailchimp.com/3.0/lists/1234/members",
    type: "POST",
    data: {email_address: "user@example.com", status: "pending"},
    // stuck here - what else should I put?
});

3 个答案:

答案 0 :(得分:-1)

尝试以下方法:

$.ajax({
    url : "https://usX.api.mailchimp.com/3.0/lists/1234/members",
    username:'username',//change this
    password:'api_key',//change this
    type: "POST",
    contentType: "application/json",
    data: {email_address: "user@example.com", status: "pending"},
    success: function(data){
         //your code to process output value from data
    }
});

或使用标题

$.ajax({
        url : "https://usX.api.mailchimp.com/3.0/lists/1234/members",
        type: "POST",
        headers: {
              'Authorization':'Basic ' + btoa("username:api_key"),
              'Content-Type':'application/json'
        },
        data: {email_address: "user@example.com", status: "pending"},
        success: function(data){
             //your code to process output value from data
        }
    });

答案 1 :(得分:-1)

以下是关于使用jQuery发送用户/密码的问题/答案:

How to use Basic Auth with jQuery and AJAX?

使用jQuery的beforeSend回调添加带有身份验证信息的HTTP标头:

beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},

您可以像这样设置内容类型:

contentType: "application/json",

- include似乎是curl的输出选项: 所有HTTP回复都包含一组通常隐藏的响应头,使用curl的--include(-i)选项显示它们以及文档的其余部分。

答案 2 :(得分:-1)

以下问题已经回答了这个问题。

Converting curl cmd to jQuery $.ajax()

$.ajax({
    url: "https://usX.api.mailchimp.com/3.0/lists/1234/members",
    beforeSend: function(xhr) { 
      xhr.setRequestHeader("Authorization", "Basic " + btoa("username:api_key")); 
    },
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    data: '{"email_address": "user@example.com", "status": "pending"}',
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});