dimanche 19 juin 2016

how to parse serlized array to a javascipt array

I have a jquery sortable list and I am serializing the result.

var data = $("#sortable").sortable('serialize');

The result looks like this item[]=41&item[]=49&item[]=51&item[]=35&item[]=58&item[]=45&item[]=32&item[]=36&item[]=26&item[]=27&item[]=33&item[]=31&item[]=29

Now I want to select each array index by using jquery $each.

    $.each(data, function(index,  value ) {

        alert( value );
    });

And I will get the error:

TypeError: Cannot use 'in' operator to search for 'length' in item[]=51&item[]=41&item[]=49&item[]=35&item[]=58&item[]=45&item[]=32&item[]=36&item[]=26&item[]=27&item[]=33&item[]=31&item[]=29

So probably I have to parse it to an array using JSON.parse():

        var data = $("#sortable").sortable('serialize');
    data=JSON.parse(data);
    $.each(data, function(index,  value ) {
        alert( value );
    });

That will causes the error

VM327:1 Uncaught SyntaxError: Unexpected token i in JSON at position 0

So it might be the problem that JSON parser expects a string with " at the beginning and the ending.

var data = $("#sortable").sortable('serialize');
    data=JSON.stringify(data);
    data=JSON.parse(data);
    $.each(data, function(index,  value ) {
        alert( value );
    });

But this will lead to the first TypeError.

Does anybody has an idea how I can parse a jquery sortable object to data array?

Aucun commentaire:

Enregistrer un commentaire