【问题标题】:how to transform from curl command to ajax request如何从 curl 命令转换为 ajax 请求
【发布时间】:2012-10-25 23:12:22
【问题描述】:

我有命令卷曲到服务器以获取信息

curl -v -H "Content-Type:application/json" -H "X-KGP-AUTH-TOKEN: a5a95c30274611e2ae10000c29bb7331" -H "X-KGP-APPID:id.kenhgiaiphap.kcloud" -H "X-KGP-APPVER:0.0.1" -H "X-KGP-DEVID:xxx" -H "X-KGP-DEVTYPE:xxx"  http://test.kenhgiaiphap.vn/kprice/account/profile/get/token

我写 ajax 来处理这个

 $.ajax({
            url: "http://test.kenhgiaiphap.vn/kprice/account/profile/get/token",
            type: "POST",
            cache: false,
            dataType: 'json',

            success: function() { alert('hello!'); },
            error: function(html) { alert(html); },
            beforeSend: setHeader
        });


        function setHeader(xhr) {
            xhr.setRequestHeader('X-KGP-AUTH-TOKEN','a5a95c30274611e2ae10000c29bb7331');
            xhr.setRequestHeader('X-KGP-APPVER', '0.0.1');
            xhr.setRequestHeader('X-KGP-DEVID', 'xxx');
            xhr.setRequestHeader('X-KGP-APPID','id.kenhgiaiphap.kcloud');
            xhr.setRequestHeader('X-KGP-DEVTYPE', 'xxx');
        }

但我有问题是

2XMLHttpRequest cannot load http://test.kenhgiaiphap.vn/kprice/account/profile/get/token. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

请求是

token

test.kenhgiaiphap.vn/kprice/account/profile/get 选项 (取消) 加载取消 文本/纯文本 jquery-1.7.2.min.js:2320 脚本 156B 0B 1.15s 39毫秒 39ms1.11s

感谢支持!

【问题讨论】:

    标签: javascript jquery curl


    【解决方案1】:

    这是一个浏览器问题。

    dataType 更改为jsonp 或将callback=? 添加到您的网址:

    http://test.kenhgiaiphap.vn/kprice/account/profile/get/token?callback=?
    

    未来参考https://stackoverflow.com/a/6396653/744255

    【讨论】:

    • 在 curl 命令中我得到了结果:{"status":"success","account":{"buy_title":"KGP ID","birthday":0,"sex":0, "电话号码":"","头像":"http:\/\/images.kenhgiaiphap.vn\/test_images\/1349882062814\/avatar\/avatar.png","密码":"","virtual_id": "1349882062814","point":0,"quota":2,"level":1,"remain":22421389413,"token":"a5a95c30274611e2ae10000c29bb7331","email":"hovanke@gmail.com","buy_link ":"http:\/\/id.kgp.vn","fullname":"hovanke"}}* 但在 ajax 中我尝试过 {"status":"failure","msg":"0107"}
    • 它有错误 Uncaught SyntaxError: Unexpected token : test.kenhgiaiphap.vn/kprice/account/profile/get/token?callback=jQuery172009154598484747112_1352171086297&_=1352171101691:1 Uncaught SyntaxError: Unexpected token : /跨度>
    • Jsonp 将无法工作,因为响应服务器不支持它。
    • 所以,你需要使用 curl 或者服务器方式。
    • 回调类似JSONP,也不起作用。正如我所说,Ajax 不是最佳选择。
    【解决方案2】:

    您不能在客户端站点“同源策略问题”中使用帖子。

    您可以使用jsonp 代替'json' 并更改为get,几乎遵循“Gabriel Santos”的建议

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-04
      • 2018-10-21
      • 2017-05-25
      • 1970-01-01
      • 2014-04-12
      • 2021-04-28
      相关资源
      最近更新 更多