Derive a JSON object from an unordered list using jQuery

I am working on this jsFiddle:

http://jsfiddle.net/8vWXZ/10/

I want to publish the order of the list items and their associated IDs in a form submitted to the server as a JSON object, but I'm not sure where to start.

+3
source share
3 answers

Because you add literal quotes to the string. Instead, "indexPos": '"' + nodeIndex + '"'just use "indexPos": nodeIndex.

+1
source

This may be a shorter approach — I wrapped your text in the gap and added a “context” class to it. Then I can use selectors much easier to pull data into a JSON-ized object.

, HTML ( LI):

<li>
    <span class="up">Up1</span>
    <span class="down">Down1</span>
    <span class="content">Item 1</span>
</li>

, , , .

: http://jsfiddle.net/Tn97g/

:

$("#submit").click(function() {
    var items=$("#reOrder li");
    var tosubmit=[];
    $(items).each(function(index, e){
        var nextItem = { "id": e.id, "val" : $(e).find(".content").text() };
        tosubmit.push(nextItem );
    });
    alert(JSON.stringify(tosubmit));
});

, , . , !

+2

Reached this (view) here:

http://jsfiddle.net/8vWXZ/15/

Unless you see in the warning, it outputs a backslash, and I'm not sure why:

[{"prodId":"item1","indexPos":"\"1\""},{"prodId":"item2","indexPos":"\"2\""},{"prodId":"item3","indexPos":"\"3\""},{"prodId":"item4","indexPos":"\"4\""}]
0
source

Source: https://habr.com/ru/post/1760068/


All Articles