为什么我不能从url中获取json对象

why cant i get the json object out of the url

本文关键字:获取 json 对象 url 不能 为什么      更新时间:2023-09-26

我有这个url,它带回了雅虎的时间。。。我猜是PST

所以我需要用javascript获取这个值。。。这是我的代码

$j.ajax({
    type: "GET",
    url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
    dataType: "jsonp",
    complete: function(data){
      console.log(data);
      }
  });

但我似乎无法从json中提取时间戳。。。我做错了什么

您使用的是complete方法,它返回XHR对象,而不是结果
您想要success:

$j.ajax({
    type: "GET",
    url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
    dataType: "jsonp",
    success: function(data){
      console.log(data.Response.Timestamp);
    }
});

来源:http://api.jquery.com/jQuery.ajax/

我认为您想使用success回调:

$j.ajax({
    type: "GET",
    url: "http://developer.yahooapis.com/TimeService/V1/getTime?appid=YahooDemo&output=json",
    dataType: "jsonp",
    success: function(data,status,xhr){
      console.log(data.Result.Timestamp);
      }
  });​

JSON看起来像{"Result":{"Timestamp":1331089290}}。也就是说,一个名为Result的对象属性,它是另一个包含属性Timestamp:的对象文字

// Use .success rather than .complete
success: function(data){
    console.log(data.Result.Timestamp);
}

javascript:

//change
dataType: "jsonp",
//to
dataType: "json", 

然后用data.Result.Timestamp提取时间戳。

使用该值时,请记住UNIX时间戳以秒为单位,而javascript日期对象以毫秒为单位。