【问题标题】:How to get JSON data into variable, parse, output as HTML [closed]如何将 JSON 数据转换为变量、解析、输出为 HTML [关闭]
【发布时间】:2016-09-03 05:18:51
【问题描述】:

我想将 JSON 数据加载到 Javascript 变量中,解析出一些数据,然后将其显示为 HTML。

JSON 数据来自 Yahoo Finance API http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail

我什至不确定如何将数据放入变量中。一旦我这样做,我想提取“名称”和“价格”并将它们输出到 HTML 表中。

【问题讨论】:

  • 这是教程或书中章节的主题,而不是 SO 问题。

标签: javascript json parsing variables


【解决方案1】:

仅使用 JavaScript:

如果你通过XMLHttpRequest请求WebService URL,你会遇到CORS问题:

XMLHttpRequest 无法加载 http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail。 请求中不存在“Access-Control-Allow-Origin”标头 资源。因此不允许访问 Origin 'null'。

但是,您可以使用https://crossorigin.me/ 服务。

然后,您应该请求:«https://crossorigin.me/http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail»。最后,这可以很容易地在 JavaScript 中使用。你不需要使用 jQuery。

我做了一个演示。

类似这样的:

(function() {
  var newXHR;

  // Helper function to make XMLHttpRequest without using jQuery or AngularJS $http service.
  function sendXHR(options) {
    //       (Modern browsers)    OR (Internet Explorer 5 or 6).
    newXHR = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP");
    if (options.sendJSON === true) {
      options.contentType = "application/json; charset=utf-8";
      options.data = JSON.stringify(options.data);
    } else {
      options.contentType = "application/x-www-form-urlencoded";
    }
    newXHR.open(options.type, options.url, options.async || true);
    newXHR.setRequestHeader("Content-Type", options.contentType);
    newXHR.send((options.type == "POST") ? options.data : null);
    newXHR.onreadystatechange = options.callback; // Will executes a function when the HTTP request state changes.
    return newXHR;
  }

  // Call the WebService by using the helper function.
  sendXHR({
    type: "GET",
    url: "https://crossorigin.me/http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail",
    callback: function() {
      if (newXHR.readyState === 4 && newXHR.status === 200) {
        var data = JSON.parse(newXHR.response); // Store the WebServices JSON data to the «data» variable.

        var table = document.getElementById("table"); // Get the table.

        // Build the HTML table.
        var html = "<table><thead>";
        html += "<th>Name</th><th>Price</th>";
        html += "</thead>";
        html += "<tbody>";
        for (i = 0; i < data.list.resources.length; i++) {
          html += "<tr><td>" + data.list.resources[i].resource.fields.name + "</td><td>" + data.list.resources[i].resource.fields.price + "</td></tr>";
        }
        html += "</tbody></table>";
        table.innerHTML = html;
      }
    }
  });
})();
#table table {
  border: solid 1px #CCCCCC;
  border-collapse: collapse;
}
#table table td {
  border: solid 1px #CCCCCC;
  padding: 5px;
}
&lt;div id="table"&gt;&lt;/div&gt;

此答案的较短版本:

https://jsfiddle.net/dannyjhonston/9okhpebk/

【讨论】:

    【解决方案2】:

    感谢您的回复。我无法让您的示例使用下面的代码。第一个警报触发,但在 .getjson 之后似乎没有任何效果。我假设一旦工作它会将 URL 加载到 displayHTML 中进行解析?

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Demo</title>
    </head>
    <body>
    <a href="http://jquery.com/">jQuery</a>
     <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    
    <script>
    alert("startting");
    var jqxhr = $.getJSON( "http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail", displayHtml)
      .fail(function() {
        alert("no response from:  http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail")
      });
    
    alert("done");
    
    </script>
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      您可以使用 jquery getJSON 方法:jQuery.getJSON( url [, data ] [, success ] ) 将 JSON 数据从 url 加载到 Javascript 变量中, 在以下示例中,displayHtml 是您要处理获取的数据的函数:

      var jqxhr = $.getJSON( "http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail", displayHtml)
            .fail(function() {
              alert("no response from:  http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail")
            });
      

      【讨论】:

        【解决方案4】:

        您可以使用 JSON.parse(strinfied_json) 在 javascript 中解析 JSON。

        JSON.parse 将 JSON 转换为普通的 javascript 对象,您可以使用 []. 运算符进行查询。

        这是一个例子:

        var stock_data_json = "{
          list: {
            meta: {
              type: \"resource-list\",
              start: 0,
              count: 1
            },
            resources: [
              {
                resource: {
                  classname: \"Quote\",
                  fields: {
                    change: \"19.061035\",
                    chg_percent: \"0.404084\",
                    day_high: \"4736.155273\",
                    day_low: \"4684.284668\",
                    issuer_name: \"NASDAQ Composite\",
                    name: \"NASDAQ Composite\",
                    price: \"4736.155273\",
                    symbol: \"^IXIC\",
                    ts: \"1462569359\",
                    type: \"index\",
                    utctime: \"2016-05-06T21:15:59+0000\",
                    volume: \"0\",
                    year_high: \"5231.940000\",
                    year_low: \"4209.760000\"
                  }
                }
              }
            ]
          }
        }"
        
        var stock_data = JSON.parse(stock_data_json)
        
        // Get the first resource
        var resource_0 = stock_data["list"]["resources"][0]["resource"];
        
        var name = resource_0["name"];
        var price = resource_0["price"];
        
        $('#name_element').text(name);
        $('#price_element').text(price);
        

        【讨论】:

          猜你喜欢
          • 2011-07-08
          • 2019-05-24
          • 2011-06-04
          • 1970-01-01
          • 2013-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多