繁体   English   中英

在PHP中读取jQuery数组

[英]read jquery array in php

我想通过php脚本中的post检索数组的值。

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脚本并在PHP端使用json_decode($_POST["userid"])进行转换将其放入PHP数组。

您要发布到PHP的对象不是特定的jQuery对象。 相反,它是一个JSON对象或一个JSON字符串。 我猜您无法像读取PHP中的常规数组那样读取该对象。

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

$phpArray = json_decode($myArray, true);

json_decode()文档: http : json_decode()

只需使用:

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
   }

暂无
暂无

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

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