简体   繁体   中英

jQuery weird JSON behaviour

I'm getting a array of the selected checkboxes and push them into an array.

After that I JSON.stringify() the array and send it to my PHP script.

But the weird thing is that when I send the array variable, it returns strange things.

Here is the code:

var _items = new Array();
$('input:checkbox:checked.item').each(function () {
   _items.push($(this).val());
});

$.ajax({
   type: 'POST',
   url: btn.data('url'),
   data: {_token: token, items: JSON.stringify(_items)},
   dataType: 'json',
   success: function () {
    //
   }
})

When I console log the `_items variable I get a array back with the selected boxes like this:

["3", "4"]

In my PHP I do:

dd(json_decode(Input::get('items')));

But the strange thing is the _items variable returns an array of this in my PHP script:

0: 2
1: 0
2: 3
3: 1
4: 1
5: 4
6: 1

When I manually created the _items variable like so: var _items = ["3", "4"]; It does return the correct array..

EDIT: When I try to send it as a array it will return the same result as the strange thing above..

EDIT2: The code where I print the PHP array with. I catch the route with laravel (this is working as it should) and then I die and dump (dd) the input. Same as $_POST['items'] :

Route::post('user/destroy/multiple', function () {
    dd(json_decode(Input::get('items')));
});

EDIT3: Strange things is when I output Input::get('items') it does return a JSON string, but for some reason I just can't json_decode it..

What can be wrong with the code...?

The problem is that you are encoding the array to Json in your javascript code, you don't have to do that, just send the array itself, the Ajax call will encode it for you. By doing that you are encoding twice the array to Json ! Replace data: {_token: token, items: JSON.stringify(_items)} by data: {_token: token, items: _items},

From http://laravel.com/docs/4.2/requests :

Note: Some JavaScript libraries such as Backbone may send input to the application as JSON. You may access this data via Input::get like normal.

So in your JavaScript you should do the following:

$.ajax({
   type: 'POST',
   url: btn.data('url'),
   data: {_token: token, items: _items},
   dataType: 'json',
   success: function () {
    //
   }
})

And in PHP you should do:

Route::post('user/destroy/multiple', function () {
    dd(Input::get('items'));
});

You want to serialize object, not array

Change your code:

var _items = {};

and something like this

$('input:checkbox:checked.item').each(function (i,v) {
    _items[i] = v;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM