【问题标题】:Converting curl command to AJAX将 curl 命令转换为 AJAX
【发布时间】:2018-02-15 01:27:36
【问题描述】:

我有一个需要使用的 API,但我不确定如何通过 AJAX 输入我的 curl 命令。任何帮助将不胜感激。

我的 curl 命令:curl -H “Authorization: Token #{auth_token}” -X GET http://localhost:3000/api/v1/baskets/

到目前为止的 AJAX:

$.ajax({
    url: "http://localhost:3000/api/v1/baskets/",
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    processData: false,
    success: function (data) {
      alert(JSON.stringify(data));
    },
    error: function(){
      alert("Cannot get data");
    }
});

更新:问题 1 已解决。除了最后一次 API 调用之外,我能够执行类似的方法来得出我需要的结果。除了网站之外,我无法在 -d 之后获取所有内容。 卷曲命令:curl -H “Authorization: Token #{auth_token}” -X GET -d ‘basket_id=#{basket_id}&price=#{price}&title=#{title}&merchant_url=#{merchant_url}&comment=#{comment}&product_url=#{product_url}&merchant_name=#{merchant_name}&color=#{color}&size=#{size}&product_image_url=#{product_image_url}’ http://localhost:3000/api/v1/baskets/add

到目前为止的 AJAX:

     $.ajax({
    url: "http://localhost:3000/api/v1/baskets/add",
    type: 'GET',
    processData: false,
    headers: { 'Authorization' : giftibly_token_string },
     data: {"basket_id": "2", "title" : "Hello There", "merchant_name" : "Target", "merchant_URL" : "http://test.com", "product_url" : "http://test.com/product" },
    success: function (data) {
      window.response = JSON.stringify(data);
      console.log(response);
    },
    error: function(){
     console.log("Cannot get data");
    }
});

浏览器结果:{"response":"Missing attributes: Basket ID, Title, Merchant Name, Merchant URL, Product URL"}

【问题讨论】:

    标签: jquery ajax api curl


    【解决方案1】:

    这应该可以工作

    $.ajax({
        url: "http://localhost:3000/api/v1/baskets/",
        type: 'GET',
        processData: false,
        headers: { 'Authorization' : 'Token #{auth_token}' },
        success: function (data) {
          alert(JSON.stringify(data));
        },
        error: function(){
          alert("Cannot get data");
        }
    });
    

    【讨论】:

    • 我的回答和你的没有区别。
    • 方法不同。 curl 使用的是 GET 而不是 POST。
    • 在 GET 中,您只能将数据作为查询字符串传递。将您的数据字段更改为数据:'basket_id=#{basket_id}&price=#{price}&title=#{title}&merchant_url=#{merchant_url}&comment=#{comment}&product_url=#{product_url}&merchant_name=#{merchant_name} &color=#{color}&size=#{size}&product_image_url=#{product_image_url}'
    猜你喜欢
    • 2017-05-18
    • 2013-12-07
    • 2016-05-20
    • 2016-12-31
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    • 1970-01-01
    相关资源
    最近更新 更多