如何将JSON数据存入变量中,解析后输出为HTML

4

这是一个教程或书籍中的一个主题或章节,而不是一个SO问题。 - user663031
4个回答

1

仅使用JavaScript:

如果您通过XMLHttpRequest请求WebService URL,则会出现CORS问题:

XMLHttpRequest无法加载http://finance.yahoo.com/webservice/v1/symbols/%5EIXIC/quote?format=json&view=detail。请求的资源上不存在“Access-Control-Allow-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;
}
<div id="table"></div>

较短的答案版本:

这个答案的简短版:

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


0

你可以使用 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);

0
你可以使用jQuery的getJSON方法:jQuery.getJSON(url[,data][,success])从一个URL加载JSON数据到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")
      });

0
感谢您的回复。我无法通过以下代码让您的示例运行起来。第一个警报出现,但似乎在.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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接