简体   繁体   中英

Get array with AJAX request and pass it into a php array

I'm struggling with the next problem: I have an ajax request that passes a variable to a PHP file. The PHP processes the variable and returns with an array. I need to get back that array so I used the AJAX success callback function but I can only print out the array, nothing more. I want to use that array.

$.ajax({
    method:  'POST',
    url:  "process.php",
    data: { data: data},
    success: function(array)
    {
        <?php echo $GLOBALS['glob']; ?> = data;
    }
});

Even though if I ref to $GLOBALS['glob'] later, it says its an undefined variable. :S please help!

On succes you assign the variable as "array" and when you try to put it in the php array u say the variable is named "data". that's your first problem.

$.ajax({
    method:  'POST',
    url:  "process.php",
    data: { data: data},
    success: function(**array**)
    {
        <?php echo $GLOBALS['glob']; ?> = **data**;
    }
});

also you try to use php on client side.. normal javascript fires after your page is loaded and the variable is allready filled on page load. in this case you cant use the variable anymore.

And i just noticed this

$.ajax({
    method:  'POST',
    url:  "process.php",
    data: { data: data},
    success: function(**array**)
    {
    <?PHP echo $GLOBALS['glob']; ?> = data 
}
});

You end the variable without assigning it it should be

<?PHP echo $GLOBALS['glob'] = ?> data  <?PHP ; ?>

but as i said php scripts are executed before javascript so when the server reads the file it only says

echo $GLOBALS['glob'] = ;

尝试从您的业务逻辑发送一个json数组。

IN your php file you need to return json string and in success callback function you can get the object you are passing through server side

Like in php file, after all processing at the end convert the array to json string

json_encode($array);

and in your success call back function try to debug console.log(array)

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