【问题标题】:Get data (json format) from another domain without jsonp从另一个没有jsonp的域获取数据(json格式)
【发布时间】:2013-12-28 21:45:21
【问题描述】:

如何从另一个域获取数据(json 格式)?
我的问题是:我想从以下位置获取数据:http://pin-codes.in/api/pincode/400001/
我曾尝试使用 CORS,但它没有用。
我的控制台是:
GET 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");
    });
 });
});

【问题讨论】:

标签: javascript jquery ajax json


【解决方案1】:

您可能不拥有另一个域,对吧?

没问题。不要介意反对者,计算一切都是好的!

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

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

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

只需测试this link(绕过跨域安全公牛$#!7)。
它将获取您请求的数据,作为包装在回调函数cbfunc 中的普通纯 json(无 jsonp)数据。

请查看this question 了解更多信息(我在 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);
}

这应该让你开始(并激励它容易)。

希望有帮助!

【讨论】:

  • jsfiddle.net/NbLYE 上一切正常。但是当我在 Firefox、Chrome 上运行你的代码时,我遇到了一个问题:RefernceError: cbfunc is not defined。这是什么意思?
  • 只是为了检查我的理解是否正确:如果您在这些浏览器(FF 和 Chrome)中运行小提琴,那么一切都可以正常工作(正如我所期望的那样),但在您自己的代码中它不会?如果是这样:您是否有一个(全局可用的)函数,名为(或引用为)cbfunc,并且该函数没有错误? cbfunc 函数是否在您实际“获取”url(操作顺序)之前定义?否则,尝试设置一个小提琴,我会看看它。
【解决方案2】:

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

你需要添加

Access-Control-Allow-Origin: *

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

编辑:从 HTTP 响应看来,您正在使用 PHP。在您的回复中使用header 函数。

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

【讨论】:

  • 查看更新的答案。如果不清楚,请在您的问题中包含您的服务器端代码,因为这就是问题所在。
  • 服务器:pin-codes.in/api/pincode/400001 不是我的。因此,我无法访问它来添加 CORS 标头。我只是在html文件中编码并打开它。
  • 什么PHP?我看到的只是 JavaScript 代码。而且我不相信 OP 可以控制 pin-codes.in 服务器。
  • 在这种情况下,您无法从浏览器执行此操作。该服务器的“所有者”未选择允许您从其他网页请求该数据。
  • 还有@MichaelGeary,PHP 来自X-Powered-By 标头。
【解决方案3】:

你不能用jquery only来做,你可以用任何server side script,比如PHP

尝试使用php

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

将以上代码保存在pincode.php中并使用jquerylike,

$(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");
            });
    });
});

另请阅读this

【讨论】:

  • 我认为:当我们在浏览器上输入链接 (pin-codes.in/api/pincode/400001) 时,它会响应 json 数据。我们可以看到它。所以,也许有办法在没有“所有者”许可的情况下解析这个响应的数据。对吗?
  • 你误会了我的想法。我的意思是也许有一种方法可以在不使用服务器端脚本的情况下解析 json 数据?因为我们输入链接就可以看到响应的json数据:pin-codes.in/api/pincode/400001
猜你喜欢
  • 2011-12-11
  • 2012-10-07
  • 1970-01-01
  • 2014-03-10
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 2012-01-25
  • 2019-03-18
相关资源
最近更新 更多