【问题标题】:How to display state to HTML with following JSON using jQuery如何使用 jQuery 使用以下 JSON 将状态显示为 HTML
【发布时间】:2017-08-17 05:10:03
【问题描述】:

JSON:

代码:

for (var i = 0; i < data.data.length; i++) {
    var output ="" + data.data[i].location.location.country + "";
}

【问题讨论】:

    标签: jquery json


    【解决方案1】:

    假设你解析的Json变量叫做data,那么:

    var data = JSON.parse("&lt;json-string&gt;");, 然后你可以像这样简单地获得状态:

    var state = data.data[0].location.location.state;

    然后您可以使用 jquery 在 HTML 中显示该状态变量,如下所示:$("div.container").html(state)

    该 jquery 代码假定您已包含对 jquery 库的脚本引用,并且您的 HTML 确实有一个类名为 container 的元素,因此类似于 `.

    如果你没有 jquery 或者只是不想使用它,你可以这样做:document.write(state)

    最后,如果您的 JSON 中有一组数据元素,那么您可以使用 for 循环来迭代每个数据元素并显示每个数据元素的状态,如下所示:

    for (var i = 0; i < data.data.length; i++) {
    var output ="" + data.data[i].location.location.state + "";
    $("div.container"+i).html(output);
    //document.write(output + "<br/>"); // without jquery 
    

    }

    【讨论】:

      【解决方案2】:

      最初,我们必须使用 $.parseJSON 解析一个 json 字符串 然后,试试这个

      Here response is your json string that is shown in image
      var data = $.parseJSON(response);
      for (var i = 0; i < data.data.length; i++) {
            var output = "" + data.data[i].location.location.country + "";
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-13
        • 1970-01-01
        • 2021-06-15
        • 2015-09-03
        • 2013-12-06
        • 2011-01-05
        • 2023-03-07
        • 2010-10-23
        • 2011-09-30
        相关资源
        最近更新 更多