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

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

If I have a list like the following:

  • Bob
  • Frank
3条回答
  •  谎友^
    谎友^ (楼主)
    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

    • Bob
    • Frank
    • Sally

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

    Hope this helped!

提交回复
热议问题