简体   繁体   中英

Sending multidimensional array via ajax

So basically here is my jQuery and HTML code for creating arrays. It basically takes each div with class setting and checks wether it has span with attribute rel, if it has, it inserts in array under array. Each new div.settign span rel attributes will be inserted to another array under same parent array.

Check this code to understand it - http://jsfiddle.net/xVuHx/ .

Pasted it also here -

jQuery(document).ready(function() {
    var rel = [];
    jQuery(".setting").each(function() {
        rel.push(jQuery(this).find('span[rel]').map(function() {
            return this.getAttribute('rel');
        }).get());
    });               
    jQuery("body").text(rel);
});​

and html -

<div class="setting">
    <span rel="Variable">Variable</span>
    <span rel="Item">Item</span>
    <span rel="Something">Something</span>
</div>
<div>
    <span rel="Smth">Smth</span>
    <span>Sec</span>
</div>
<div class="setting">
    <span>Second</span>
    <span rel="first">First</span>
    <span rel="Third">Third</span>
</div>

it's working great and displays two arrays - one with 3 elements and one with two, but when I try to pass it to PHP file via ajax, ti gives me [object Object] with var_dump($array); . Also I tried to do foreach, but it told me that invalid arguments were passed to foreach statement, so I guess I'm sending the array to ajax incorrectly or the Array is made incorrectly.

Here is my ajax code -

var myArray = jQuery(this).sortable("serialize") + "&type="+rel+"&action=update_homepage";
jQuery.post("'.admin_url("admin-ajax.php").'", myArray, function(response){
   var info = response.slice(0,-1);
});

This ajax code is made via wordpress, so its ajax requests differs a little bit from default AJAX requests.

Could you please check what exactly could be the problem?

EDIT:

Just tried to output with print_r($myArray); in php side, it outputs empty string.

Check format of posted data in AJAX request in browser console (section network).

You can find information about opening the console in your browser in this stackexchange question .

JSON-js - JSON in JavaScript.

To convert an object to JSON, use JSON.stringify :

var json_text = JSON.stringify(your_object, null, 2);

Encode your array to JSON and then send it with Ajax request. To decode JSON in PHP use json_decode

最好将其转换为json

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