【问题标题】:Use jQuery to convert JSON array to HTML bulleted list使用 jQuery 将 JSON 数组转换为 HTML 项目符号列表
【发布时间】:2010-11-15 22:13:31
【问题描述】:

如何转换以 JSON 格式表示的字符串数组并使用 jQuery 将其转换为 HTML 项目符号列表?

【问题讨论】:

标签: jquery json


【解决方案1】:
var ul = $('<ul>').appendTo('body');
var json = { items: ['item 1', 'item 2', 'item 3'] };
$(json.items).each(function(index, item) {
    ul.append(
        $(document.createElement('li')).text(item)
    );
});

就使用 AJAX 从服务器获取 JSON 而言,您可以使用 $.getJSON() 函数。

Live demo.

【讨论】:

  • 我以前从未见过 jsfiddle.net。我同意。
  • @climbage,这是一个非常好的网站,允许支持流行框架的快速 javascript 模型。
【解决方案2】:
<script language="JavaScript" type="text/javascript">

// Here is the code I use.  You should be able to adapt it to your needs.

function process_test_json() {
  var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\ideas_org\\wwwroot\\chapter0-2\\LastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\ideas_org\\wwwroot"}}};

var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
alert( htmlStr );
$( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
$("div#outAsHtml").text( $("div#out").html() ); 
}
function recurse( data ) {
  var htmlRetStr = "<ul class='recurseObj' >"; 
  for (var key in data) {
        if (typeof(data[key])== 'object' && data[key] != null) {
            htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
            htmlRetStr += recurse( data[key] );
            htmlRetStr += '</ul  ></li   >';
        } else {
            htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>&quot;' + data[key] + '&quot;</li  >' );
        }
  };
  htmlRetStr += '</ul >';    
  return( htmlRetStr );
}

</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>

<!-- QUESTION: Maybe some one with more jquery experience 
could convert this to a shorter / pure jquery method -->

【讨论】:

  • 我没有考虑递归。谢谢。
【解决方案3】:

这样的 JSON 字符串如下所示:

'["foo","bar","base","ball"]'

您可以通过调用 JSON.parse() 将其解析为 Javascript 数组对象,遍历该数组并插入字符串。

var jsonstring = '["foo","bar","base","ball"]',
    arr = JSON.parse(jsonstring),
    len = arr.length;

while(len--) {
    $('<li>', { 
        text:   arr[len]
    }).appendTo('ul');
}

【讨论】:

    【解决方案4】:

    使用 jQuery jPut 插件。只需创建一个 html 模板并调用您的 json 文件。也可以通过jPut(ajax_url)调用ajax文件

    http://plugins.jquery.com/jput/

    <script>
        $(document).ready(function(){
            var json = [{"name": "item1","link":"link1"},{"name": "item2","link":"link2"}];
    
              //jPut code 
              $("#menu").jPut({
                jsonData:json,
                name:"template",
              });
        });
    </script>
    
    <body>    
            <!-- jput template, the li that you want to append to ul-->
            <div jput="template">
               <li><a href="http://yourdomain.com/{{link}}">{{name}}</a></li>
            </div>
    
            <!-- your main ul -->
            <ul id="menu">
            </ul>
    </body>
    

    【讨论】:

    • jput 不是有效属性。
    • @Benio 在您的 HTML 中添加 jput.js。
    • jput,如您在示例代码中所示,不是有效属性。如果你想使用自定义属性,你应该使用a custom data attribute,比如data-jput,否则它不是一个有效的HTML代码。
    【解决方案5】:

    如果你的 json 字符串在 stringArr 中:

    $.each(stringArr, function(idx, val) {
       $('<li></li>').html(val);
    }
    

    或者这些行中的某些东西应该这样做。

    【讨论】:

      【解决方案6】:

      可能是这样的?我还没有测试过,但它应该可以工作。

      ul = $("<ul/>");
      $(json_arr).each(function(){
          $("<li/>").text(this).appendTo(ul);
      });
      
      // add ul to DOM
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-06
        • 2011-09-08
        • 1970-01-01
        • 2023-03-20
        • 2019-05-01
        • 2023-03-18
        • 2021-10-21
        相关资源
        最近更新 更多