【问题标题】:$.getJSON is not entering the function and not getting any data$.getJSON 没有进入函数也没有得到任何数据
【发布时间】:2012-06-14 10:07:36
【问题描述】:

我有以下 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 函数,“enetered getJSON”警报没有触发。

怎么了?

解决了。谢谢大家:)

【问题讨论】:

标签: javascript jquery json


【解决方案1】:

我认为你无法做到这一点。对于跨域 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) 

【讨论】:

    【解决方案2】:

    您不能从另一个域获取 JSON,除非它们支持 CORS,因为 same origin policy

    api是否支持jsonp

    【讨论】:

      【解决方案3】:

      你检查过控制台吗?您可能遇到了访问控制来源错误

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

      【讨论】:

      • 这里的修复是用常规的 jQuery ajax 调用替换 getJSON 并将它的 dataType 设置为 jsonp
      • 只有在站点实际响应正确的 JSONP 响应时才有效;纯 JSON 不起作用。
      • 服务器也必须支持 JSONP,如果设置正确,getJSON 将执行“JSONP 请求”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      相关资源
      最近更新 更多