如何从ajax调用传递的php访问数组中的所有元素?

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.

var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
    $("button").click(function () {
        $.ajax({
            type: "POST",
            url: "getResult.php",
            data: {
                testData: data
            },
            success: function (data, status) {
                alert("Data: " + data + "
Status: " + status);
            }
        });
        return false;
    });
});

The server side [PHP] code is

$myArray = $_POST["testData"];
echo $myArray; 

However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements? Pls help.

What you need to do is convert the JavaScript array to JSON and then send over that JSON. On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.

On your client side change one line:

data: {testData : JSON.stringify(data)},

On your server side do:

$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));

JS:

JSON.stringify(data)

PHP:

$myArray = json_decode($_POST['data']);

For simple structures you can use jQuery Param

data : $.param({testData:data})

With this you should be able to access your data with

echo $_POST["testData"][0]...[2];

Try this when passing JS vars by ajax.

use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.

you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.

use :

 var data = ['test1','test2','test3'];
 data = JSON.stringfy(data);

at the PHP:

     $data = var_post('test_data');
     $data=json_decode($data);
     $print_r($data);