2016-07-24 25 views
0

請幫助我,我不能從我的主頁中獲取數據 我的AJAX請求:在我的主頁我如何請求從我的主頁訪問我的json.json數據?

$.ajax({ 
       url:"http://example.com/json.json?jsoncallback=?", 
       type:"GET", 
       dataType:"jsonp", 
       beforeSend:function(){ 
        console.log("before send"); 
       }, 
       success:function(data,status){ 
       console.log("success"); 
       } 
      }); 

而且json.json文件

> { "firstName": "John", "lastName": "Smith", "isAlive": true, 
> "age": 25, "address": { 
>  "streetAddress": "21 2nd Street", 
>  "city": "New York", 
>  "state": "NY", 
>  "postalCode": "10021-3100" }, "phoneNumbers": [ 
>  { 
>  "type": "home", 
>  "number": "212 555-1234" 
>  }, 
>  { 
>  "type": "office", 
>  "number": "646 555-4567" 
>  }, 
>  { 
>  "type": "mobile", 
>  "number": "123 456-7890" 
>  } ], "children": [], "spouse": null } 

請建議我通過谷歌和搜索嘗試了很多這裏但不明白

回答

0

我觀察到的錯誤是使用數據類型jsonp,其中原始數據是json格式。 因此,如果下面的代碼塊不是跨域請求,它應該可以很好地工作。

$.ajax({ 
     url : "http://example.com/json.json", 
     type : "GET", 
     success:function(data,status){ 
     console.log(data); //json data from the requested url 
     }, 
     failure:(xhr,responseText,status){ 
     //failure block 
     } 
    }); 

但在你的情況,如果它是一個跨域請求,你沒有你的JSON數據的回調函數包圍,下面的代碼塊將工作做好,但你必須導入YQL庫在您的網頁https://github.com/hail2u/jquery.query-yql

function getCrossDomainData(){ 
    try{ 
     var site = "http://example.com/json.json"; 
     var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from json where url="' + site + '"') + '&format=json&callback=cbFunc'; 
     $.ajax({ 
      url: url, 
      dataType: 'jsonp', 
     }); 
     function cbFunc(data) { 
      // get the data in this block 
     } 
    }catch(err){ 
     console.log("Err in getCrossDomainData : "+err); 
    } 
} 
相關問題