首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析JSON服务器响应

解析JSON服务器响应
EN

Stack Overflow用户
提问于 2014-01-16 02:26:00
回答 2查看 3.5K关注 0票数 0

我正在使用wunderground API来练习我的JS,我有一个问题,那就是当我进行调用时,如何解析他们返回的JSON响应。

我在下面有一个简单的函数,我调用URL并接收响应并将其发送到iframe。在iframe中,我看到了原始的JSON。我想知道的是如何解析JSON并在iframe中显示解析后的信息。(如果更简单,则为div )

我假设它是JSON.parse的一些变体,但我还没能让它以我想要的方式工作。

此外,我更喜欢避免jquery,我想使用常规的JS。

代码语言:javascript
复制
  function conditions(){
    var zip = document.getElementById("zip").value;
    var url = "http://api.wunderground.com/api/<API_KEY>/conditions/q/" + zip + ".json"
    {
    window.open(url,"frame");
    }

更新:这就是我现在所拥有的。我知道我的实现是错误的。我也仍然遇到同样的问题,不得不绕过Chromes安全性进行测试。如有任何建议,欢迎光临。

代码语言:javascript
复制
function conditions() {

GET_JSON = function(callback){
var c = document.getElementById("zip").value;
var x = new String("http://api.wunderground.com/api/KEY/conditions/q/" + c + ".json" +"?callback=JSONCallback");
    var req = new XMLHttpRequest();
    req.open("GET", x, true);
    req.onreadystatechange = function(){
        if(this.readyState==4){
            callback(JSON.parse(req.responseText));
        }
    }
    req.send(null);
}
JSONCallback = function(JSONObj){
    alert(JSONObj);
};
GET_JSON(JSONCallback);
}
EN

回答 2

Stack Overflow用户

发布于 2014-01-16 04:00:55

不知道wunderground是否使用与wiki media相同的API。然而,这里是一个如何执行JSONP(在这里阅读:JSONP)的示例,它允许您在跨域请求的情况下查询页面。

如果您阅读这个问题:Trying to search wunderground locations with javascript, jquery, and html,您可以看到建议使用JSONP。因此,对以下示例进行一个小的修改就可以让您开始了解从站点获取结果所需的操作。

代码语言:javascript
复制
<!DOCTYPE html>
<html>
   <head>
      <title>Wikipedia JSON Grabber</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <style>
         div{
            position: relative;
            background-color: white;
         }
      </style>
      <script>
         // Function call the Wikipedia API
         function doFetch() {
            var tmpScript = document.createElement("script");
            tmpScript.src = "http://en.wikipedia.org/w/api.php?" +
                    "format=json" +
                    "&callback=gotFetch" +
                    "&action=query" +
                    "&titles=json" +
                    "&prop=revisions" +
                    "&rvprop=content";
            document.body.appendChild(tmpScript);
         }

         // Callback to trigger whenever the API responds
         function gotFetch(data) {
            var parent = document.createElement("div"),
                    depth = 0;
            document.body.appendChild(parent);
            console.log("Got data");
            for (var t in data) {
               console.log(data[t]);
               printData(data, parent, depth);
            }
         }

         // Recursively print out the object received to console
         function printData(data, parent, depth) {
            for (var prop in data) {

               var newDiv = document.createElement("div");
               newDiv.style.left = (10 * (depth++)) + "px";
               parent.appendChild(newDiv);

               if (typeof data[prop] === "object") {
                  newDiv.innerHTML = prop;
                  printData(data[prop], newDiv, depth);
               } else {
                  newDiv.innerHTML = data[prop];
               }
            }
         }

         function main() {
            doFetch();
         }
      </script>
   </head>
   <body onload="main();">
      <div></div>
   </body>
</html>
票数 0
EN

Stack Overflow用户

发布于 2014-01-16 05:37:12

我从wunderground得到了一个示例json url:

代码语言:javascript
复制
var url = "http://api.wunderground.com/api/<API_KEY>/conditions/q/CA/San_Francisco.json";

它的输出json是:

代码语言:javascript
复制
{"response":{"version":"0.1","termsofService":"http://www.wunderground.com/weather/api/d/terms.html","features":{"conditions":1}},"current_observation":{"image":{"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png","title":"Weather Underground","link":"http://www.wunderground.com"},"display_location":{"full":"San Francisco, CA","city":"San Francisco","state":"CA","state_name":"California","country":"US","country_iso3166":"US","zip":"94101","magic":"1","wmo":"99999","latitude":"37.77500916","longitude":"-122.41825867","elevation":"47.00000000"},"observation_location":{"full":"SOMA - Near Van Ness, San Francisco, California","city":"SOMA - Near Van Ness, San Francisco","state":"California","country":"US","country_iso3166":"US","latitude":"37.773285","longitude":"-122.417725","elevation":"49 ft"},"estimated":{},"station_id":"KCASANFR58","observation_time":"Last Updated on January 15, 12:12 PM PST","observation_time_rfc822":"Wed, 15 Jan 2014 12:12:06 -0800","observation_epoch":"1389816726","local_time_rfc822":"Wed, 15 Jan 2014 12:12:10 -0800","local_epoch":"1389816730","local_tz_short":"PST","local_tz_long":"America/Los_Angeles","local_tz_offset":"-0800","weather":"Partly Cloudy","temperature_string":"69.8 F (21.0 C)","temp_f":69.8,"temp_c":21.0,"relative_humidity":"28%","wind_string":"From the WNW at 2.0 MPH","wind_dir":"WNW","wind_degrees":295,"wind_mph":2.0,"wind_gust_mph":0,"wind_kph":3.2,"wind_gust_kph":0,"pressure_mb":"1026","pressure_in":"30.29","pressure_trend":"-","dewpoint_string":"35 F (2 C)","dewpoint_f":35,"dewpoint_c":2,"heat_index_string":"NA","heat_index_f":"NA","heat_index_c":"NA","windchill_string":"NA","windchill_f":"NA","windchill_c":"NA","feelslike_string":"69.8 F (21.0 C)","feelslike_f":"69.8","feelslike_c":"21.0","visibility_mi":"10.0","visibility_km":"16.1","solarradiation":"--","UV":"3","precip_1hr_string":"0.00 in ( 0 mm)","precip_1hr_in":"0.00","precip_1hr_metric":" 0","precip_today_string":"0.00 in (0 mm)","precip_today_in":"0.00","precip_today_metric":"0","icon":"partlycloudy","icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif","forecast_url":"http://www.wunderground.com/US/CA/San_Francisco.html","history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KCASANFR58","ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725"}}

那么现在我们该如何获得这个输出呢!?我们有两种不同的解决方案:

1-旧的解决方案是使用ajax将json作为字符串获取,然后将其解析为对象,如下所示:

代码语言:javascript
复制
GET_JSON = function(callback){
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.onreadystatechange = function(){
        if(this.readyState==4){
            callback(JSON.parse(req.responseText));
        }
    }
    req.send(null);
}
JSONCallback = function(JSONObj){
    alert(JSONObj);
};
GET_JSON(JSONCallback);

但这里的问题是,如果你在你的网站上这样做,你会面临这个错误:

代码语言:javascript
复制
No 'Access-Control-Allow-Origin' header is present on the requested resource.
    Origin 'http://mydomain.com' is therefore not allowed access.

2-没问题,wunderground weather api支持JSONP,它会帮助我们解决这个问题,我们只需要做一个JSONP调用,这里的棘手之处在于,我们将不再使用常规的ajax解决方案:

代码语言:javascript
复制
GET_JSON = function(callback){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url + "?callback=" + callback;
    document.body.appendChild(script);
}
window.JSONCallback = function(JSONObj){
    alert(JSONObj);
};
GET_JSON("JSONCallback");

有一个非常棘手的点是非常重要的。如果你检查最后一行,而不是传递回调对象作为参数,我已经传递了它的名称,为什么?

答案是,如果我们想要有一个JSONP调用,我们必须用callback queryString传递回调函数的名称。如下所示:

代码语言:javascript
复制
url = "http:// ... .json?callback=JSONCallback";

这就是访问json对象所需了解的全部内容,而不需要解析字符串。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21145408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档