简体   繁体   English

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

[英]How to pass JS array via POST AJAX to 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: 在我的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? 它只是返回垃圾...所以我的问题是如何通过AJAX传递数组以发布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'] 因为将字符串相关的函数trimmysql_real_escape_string应用于数组 $_POST['var_ids']最有可能获得意外结果

As long as it is just an array of integers - the only mysql sanitize you need is casting to int: 只要它只是一个整数数组-所需的唯一mysql清理是强制转换为int:

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

$_POST['var_ids'] is an array in your example on the PHP side. $ _POST ['var_ids']是示例中PHP端的数组。 You can only call trim and mysql_real_escape_string on strings not arrays. 您只能在字符串而不是数组上调用trim和mysql_real_escape_string。 Try this in php: 尝试在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. Viola,$ postData现在是一个带有修剪和转义值的PHP数组。

It's in the docs about 1/4 of a way down titled pass arrays of data to the server 文档中,大约有1/4的方式将标题数据数组传递给服务器

    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);

    }); 

使它成为json_encoded数组...然后,您可以正确地对json_decode()数组。

You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way. 最好将数组转换为JSON对象(Javascript对象表示法)并以这种方式发送。

Javascript JSON Instructions Javascript JSON指令

JSON PHP Reference JSON PHP参考

您可以使用键items[]来发布每个项目,然后可以以$_POST['items']访问数组,也可以序列化数组,发送并在PHP中进行JSON.stringify序列化( JSON.stringify和PHP json_decode ) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM