How do I convert the items of an LI into a json object using jquery?

前端 未结 3 1365
别那么骄傲
别那么骄傲 2021-02-04 13:59

If I have a list like the following:

  • Bob
  • Frank
相关标签:
3条回答
  • 2021-02-04 14:18
    var items = [];
    
    $('ul.nameList').children().each(function() {
      var $this = $(this);
      var item = { id: $this.attr('value'), title: $this.html() };
      items.push(item);
    });
    
    0 讨论(0)
  • 2021-02-04 14:25

    jQuery actually has something built-in for building the array: map()

    var items = $('.nameList').find('li').map(function() {
      var item = { };
    
      item.id = this.value;
      item.title = $(this).text();
    
      return item;
    });
    

    That will build an array of objects matching the JSON structure you're after. Then, to JSON serialize that, use JSON.stringify which is built into newer browsers and available for older ones by including json2.js:

    // Produces [{'id':1,'title':'bob'},{etc},{etc}]
    var json = JSON.stringify(items);
    

    Also keep in mind that $.post() automatically serializes an object data parameter, as key1=value1&key2=value2&etc. Unless you strictly need JSON on the server-side, the JSON serialization step may not be necessary.

    0 讨论(0)
  • 2021-02-04 14:27


    You can simply push these to a JSON object, Here is how -

       // create a blank array
        var mylist = [];
    
        // loop trough the li
        $("ul.nameList > li").each(function () {    
        //push element data to the array
            mylist.push({
                "id": $(this).attr("value"),
                "title": $(this).text()
            });
        })
    
        // then you can simply pass it to the post method 
        $.post("myhandler.php", { list: mylist }, function (data) {
            // recived data
       })
    

    And of course the your html

    <ul class="nameList">
        <li value="1">Bob</li>
        <li value="2">Frank</li>
        <li value="3">Sally</li>
    </ul>
    

    Working example - http://jsfiddle.net/mohammadwali/tkhb5/

    Hope this helped!

    0 讨论(0)
提交回复
热议问题