通过Yahoo API YQL获取JSONP数据 - Javascript

时间:2016-03-15 07:19:35

标签: javascript json jsonp yql yahoo-api

我有一个来自我的供应商的api返回JSON数据api如下: - http://shipdesk.in/mobile/mobile_quick.php?country=IN&to_country=IN&pin=560001&weight=2.5&unit=KG&need_cod=No&to_pin=700001

现在这个API没有JSONP编码,因此我无法将&callback=processJSON附加到此。

我已经读过雅虎Api可以将它从JSON转换为JSONP,我可以在我的网站上使用它,但我没有成功。

此外,我的网站有几个限制,所以我不能为此编写PHP代码。它必须在Javascript中完成。

可用的JSONP代码(另一个例子)如下: -

<span id='test'>nothing</span>

<script>
    function processJSON(json) {
        // Do something with the JSON response

        result = JSON.stringify(json);

        //alert(result);
        document.getElementById("test").innerHTML = result;

    };
</script>

<script src='http://api.flickr.com/services/feeds/photos_public.gne?tags=monkey&tagmode=any&format=json&jsoncallback=processJSON'></script>

非常感谢任何想法,链接,教程和代码片段。

1 个答案:

答案 0 :(得分:0)

可能这是你的预期。 使用Yahoo API将普通JSON转换为JSONP类型(yahoo link):

<span id='test'>nothing</span>

<script>
/* function processJSON (json) {
  // Do something with the JSON response

result=JSON.stringify(json);

//alert(result);
document.getElementById("test").innerHTML = result;

};
*/ 
</script>

<script>
var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'http://shipdesk.in/mobile/mobile_quick.php?country=IN&to_country=IN&pin=560001&weight=2.5&unit=KG&need_cod=No&to_pin=700001';

$.ajax({
  'url': yql_url,
  'data': {
    'q': 'SELECT * FROM json WHERE url="'+url+'"',
    'format': 'json',
    'jsonCompat': 'new',
  },
  'dataType': 'jsonp',
  'success': function(response) {
    console.log(response);
    document.getElementById("test").innerHTML = JSON.stringify(response);
  },
  'error': function(error) {
    document.getElementById("test").innerHTML = "error";
  }
});
</script>

新脚本标记使用我们的网址对yahoo api进行ajax调用。 但您应该信任雅虎的API响应数据。

希望这会有所帮助。

相关问题