如何通过POST AJAX将JS数组传递给PHP?

Here is my code:

var var_ids = new Array();
var i = 0;
jQuery("select").each(function() {
var_ids[i] = jQuery("option:selected",this).val();
i++;
}

var $data = {
action: "do_something",
var_ids: var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
    alert(response);

}); 

And in my php:

$ids = mysql_real_escape_string(trim($_POST['var_ids']));
exit(print_r($ids));

And it just returns garbage...So my question is how to pass an array via AJAX to post php?

Thank you.

Most likely you get unexpected results because you apply string-related functions trim and mysql_real_escape_string to array $_POST['var_ids']

As long as it is just an array of integers - the only mysql sanitize you need is casting to int:

$ids = array_map('intval', $_POST['var_ids']);
print_r($ids);

It's in the docs about 1/4 of a way down titled pass arrays of data to the server

    var var_ids = new Array('10','12','13');
    var $data = {
    action: "do_something",
    'var_ids[]': var_ids,
    };
    jQuery.post(doajax.ajaxurl, $data, function(response) {
        alert(response);

    }); 

Make it json_encoded array ... And then You can json_decode() the array properly.

You can either post each of the items with the key items[], then you could access the array as $_POST['items'] or you can serialize the array, send it and unserialize in PHP (JSON.stringify and PHP json_decode).

You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way.

Javascript JSON Instructions

JSON PHP Reference

$_POST['var_ids'] is an array in your example on the PHP side. You can only call trim and mysql_real_escape_string on strings not arrays. Try this in php:

$postData = isset($_POST['var_ids'])?$_POST['var_ids']):null;
if(is_array($postData)){
    foreach($postData as $key=>$value){
        $postData[$key] =  mysql_real_escape_string(trim($value));
    }
}

Viola, $postData is now a PHP array with trimmed and escaped values.