简体   繁体   中英

jQuery's .ajax is losing data?

Okay I'm fiddling around with this for hours and getting frustrated. I want to build an application form with ajax. I pass an associative array with huge nested arrays in it:

[
    "foo": x,
    "bar": y,
     // ...
]

Here is an example what x or y can look like (it's way too huge to post it here). It's basically just an object with nested arrays in it:

{
    lastModified: 1243245656
    some: x
    other: y
    keys: z
    feed: [ ... ]
    items: [ ... ]
    // ...
}

So my associative array added_toons would like this:

[
    "foo": {
        lastModified: 1243245656
        some: x
        other: y
        keys: z
        feed: [ ... ]
        items: [ ... ]
        // ...
    },
    "bar": {
        lastModified: 1243245656
        some: x
        other: y
        keys: z
        feed: [ ... ]
        items: [ ... ]
        // ...
    },
    // ..
]

Here comes the problem: When I evaluate my array right before I pass it with ajax everything is fine. As soon as I receive it in my php backend there are missing arrays within each toon . items and feed for example.
I really have no idea what is happening.

So I'm asking for some help to troubleshoot this. AFAIK it shouldn't be a problem with escaping since jQuery already does this for me.


My JS code

    console.info(added_toons); // everything is fine here
    $.ajax({
        url: '...',
        type: 'post',
        data: {
            'action': 'submit',
             // ...
            'toons': added_toons
        },
        success: function (data, status) {
            // ...
        },
        error: function (xhr, desc, err) {
            // ..
        }
    });

My PHP code

<?php
if ($_POST['action'] == 'submit') {
    // when I here evaluate $_POST it contains `toons` 
    // but each `toon` is missing keys
}

Try this way to set JSON.stringify for your added_toons

data: {
        'action': 'submit',
         //stringify is important to send array of objects
        'toons': JSON.stringify(added_toons) 
      },

See about JSON.stringify() here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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