簡體   English   中英

從沒有jsonp的另一個域獲取數據(json格式)

[英]Get data (json format) from another domain without jsonp

我如何從另一個域獲取數據(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");
    });
 });
});

您可能不擁有另一個域嗎?

一點問題 沒有 不要介意反對者,在計算一切時都是肯定的!

只需使用你的服務器上的一個簡單的代理或可考慮YQL

這個簡單的查詢將起作用:

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

只需測試此鏈接 (繞過跨域安全性Bull $#!7)。
它會以回調函數cbfunc獲取您請求的數據作為普通的普通json(無jsonp)數據。

看看這個問題以獲取更多信息(我在SO上做了很多yql scrape答案)。


更新:

這是演示整個過程的粗略小提琴:因此,您輸入一個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使用jquery only ,可以使用任何server side scriptPHP

嘗試使用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");
            });
    });
});

另請閱讀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM