在php中阅读jquery数组


read jquery array in php

我试图通过post在PHP脚本中检索数组的值。

var data = [];
table.rows({ selected: true }).every(function(index){
    // Get and store row ID
    data.push(this.data()[0]);  //create a 1 dimensional array
});
//send data via ajax    
$.ajax({                                      
      url: '/...../...',                  
      type: 'POST',   
      data: {userid:data},                      
      dataType: 'json',                       

在我的PHP脚本到目前为止,我无法解码数组。我试过很多方法

$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
    $userid= $value;             //for now just trying to read single item 
}

我试过print_r($myArray );这成功地将数组内容打印到屏幕上。

我正在尝试检索处理的值!请告诉我正确的方向

我不认为PHP会识别数组,你已经称为"数据"作为一个数组。难道你不能把数据从你的表行变成一个JavaScript对象的值,编码为JSON字符串,然后发布到你的PHP脚本和使用 json_decode($_POST["userid"]) 在PHP端转换成PHP数组。

您发布到PHP的对象不是一个特定的jQuery对象。相反,它是一个JSON对象,或者说是一个JSON字符串。我猜你不能像在PHP中读取普通数组那样读取这个对象。

您可能想尝试用json_decode()解码字符串。使用true作为函数参数,它将返回一个php数组,如这个stackoverflow答案https://stackoverflow.com/a/6964549/6710876

所建议的那样
$phpArray = json_decode($myArray, true);

json_decode()文档:http://php.net/manual/en/function.json-decode.php

直接使用:

echo json_encode($myArray);

您的foreach正在循环不存在的$arr。你的数组被设置为$myArray,所以在for中使用它。

$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
    $userid= $value;             //for now just trying to read single item 
}

我相信你也应该能够找到你的值在$_POST

根据您的var_dump:

array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }

,如果我们假设"assssssss,camo,castor"是3个不同的用户名。你应该这样做:

 $userids=explode(",",$myArray->userid);
    foreach($userids as $userid){
        // use $userid
   }