2012-06-11 58 views
0

我有以下的jQuery代碼:

$(document).ready(function() 
{ 
    $('button').click(function() 
    { 
     $.getJSON('http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/server/status?output=json', function(json) 
     { 
      alert("Entered getJSON"); 

      $("#output").append("working...");    
      if(json.status.indexOf("success")===0) 
      { 
       alert("success"); 
       $.each(json.results, function(i, data) 
       { 
        $("#output").append(data.text); 
       }); 
      }else 
      { 
       alert("Failed to load url"); 
      } 
     }); 
    }); 
}); 

是從URL拉JSON的樣子:

{"worldServerStatus": { 
"customMessage": "", 
"lastChangedDate": { 
    "date": 31, 
    "day": 4, 
    "hours": 17, 
    "minutes": 48, 
    "month": 4, 
    "nanos": 0, 
    "seconds": 32, 
    "time": 1338486512000, 
    "timezoneOffset": 0, 
    "year": 112 
}, 
"localizedMessage": "The servers are currently up and running.", 
"message": "ALL_SYSTEMS_GO", 
"status": "UP" 
}} 

我的jQuery只是拒絕進入$ .getJSON函數,「發送getJSON」警告不會觸發。

出了什麼問題?

已解決。謝謝大家:)

+5

是您的網站託管在你試圖從檢索JSON同一個域? –

+1

不,它託管在http://mlp-nfsw.net – Skye

+0

您不能將這樣的AJAX呼叫轉移到與您自己不同的域。 – Pointy

回答

3

你檢查了控制檯嗎?你可能會從一個訪問控制原產錯誤

jQuery.getJSON - Access-Control-Allow-Origin Issue

+0

這裏的修正是用常規的jQuery ajax調用替換getJSON,並將它的dataType設置爲jsonp – jakee

+0

,這隻有在網站實際響應正確的JSONP響應時纔會起作用;普通的JSON將無法工作。 – Pointy

+0

服務器也必須支持JSONP,如果設置正確,'getJSON'將執行「JSONP請求」。 –

0

我不認爲你能做到這一點。對於跨域ajax請求,api提供者必須使用jsonp。你可以做的是爲請求創建一個php文件。讓我們稱之爲request.php

<?php 
/* gets the data from a URL */ 
function get_data($url) 
{ 
    $ch = curl_init(); 
    $timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 

$query = $_SERVER['QUERY_STRING']; 
$url = ('http://world.needforspeed.com/SpeedAPI/ws/game/nfsw/server/status?'.$query); 

echo get_data($url); 

?> 

然後將文件在JavaScript

$.getJSON('http://myserver.com/request.php?output=json', function(json)