在没有jsonp的情况下从另一个域获取数据(json格式)



如何从另一个域获取数据(json格式)
我的问题是:我想从以下位置获取数据:http://pin-codes.in/api/pincode/400001/
我试过使用CORS,但没有成功
我的控制台是:
得到http://pin-codes.in/api/pincode/400001[HTTP/1.1 200 OK 780ms]
错误错误
我的客户端脚本代码:

$(document).ready(function() {
 $("#get_data_btn").click(function() {
   var data_path = "http://pin-codes.in/api/pincode/400001";
   $.getJSON(data_path, null)
    .done(function(data) {
      console.log("Success: " + data.status);
    })
    .fail(function(jqxhr, textStatus, error) {
      console.log("Error Error");
    });
 });
});

您可能不拥有其他域,对吗?

没有问题 。别介意反对者,在计算中,一切都是一场骗局

只需在您的服务器上使用一个简单的代理,或者查看YQL。

这个简单的查询将起作用:

select * from json where url="http://pin-codes.in/api/pincode/400001/ "

只需测试此链接(绕过跨域安全牛市$#!7)
它将获得您请求的数据,作为回调函数cbfunc中封装的普通纯json(无jsonp)数据。

看看这个问题,了解更多信息(我在SO上做了很多yql抓取答案)。


更新:

这里有一个粗糙的小提琴演示了整个过程:所以你输入一个url,点击fetch,然后观看魔术的发生:http://jsfiddle.net/NbLYE/

function getJSON(url) {  //quick and dirty
  var script = document.createElement('script');
  script.setAttribute('src', url);
  script.setAttribute('type', 'text/javascript');
  document.getElementsByTagName('head')[0].appendChild(script);
}
function cbfunc(json){     //the callback function
   if(json.query.count){ 
      var data=json.query.results.json;
      // do your work here, like for example:
      //document.getElementById('output').innerHTML=data.toSource();
   } else {
      alert('Error: nothing found'); return false;
   }
}
function fetch(url){         //scrape the url you'd want
   var yql="select * " + 
           " from json" +
           " where url='" + url + "';";
   yql="http://query.yahooapis.com/v1/public/yql?q=" +
       encodeURIComponent(yql) +
       "&format=json" +
       "&callback=cbfunc";
   getJSON(yql);
}

这应该会让你开始(并激励你,因为这很容易)。

希望这能有所帮助!

您的服务器上没有正确的CORS头。

您需要添加

Access-Control-Allow-Origin: *

(或类似的)服务器端响应。

编辑:从HTTP响应中,您似乎正在使用PHP。在响应中使用标头函数。

<?php header('Access-Control-Allow-Origin: *'); ?>

您不能使用jquery only,您可以使用任何类似PHPserver side script

尝试使用php

<?php
    echo file_get_contents('http://pin-codes.in/api/pincode/400001');
?>

将上述代码保存在pincode.php中,并使用类似jquery

$(document).ready(function() {
    $("#get_data_btn").click(function() {
        var data_path = "pincode.php";
        $.getJSON(data_path, null)
            .done(function(data) {
                console.log("Success: " + data.status);
            })
            .fail(function(jqxhr, textStatus, error) {
                console.log("Error Error");
            });
    });
});

另请阅读此

最新更新