繁体   English   中英

通过带有索引的jquery ajax发送php数组并接收数组值

[英]send php array through jquery ajax with index and recieve the array value

我正在进行在线考试测试,其中childArray []包含表的每一行的数据,而parrentArray []包含childArray []的数量。 我想从ParentArray获取每个childArray的值,并通过ajax传递索引。

<?php 
 $childArray1[]=[1,question,optionA,optionB,optionC];
 $childArray2[]=[1,question,optionA,optionB,optionC];
 $parentArray[]=[$childArray1,$childArray2];
?>

<script>
$(document).ready(function(){
    var counter=0;
    $("#ButtonNext").click(function(){
       $.ajax({
           type:"POST",
           url: "ChangeQuestionProcess.php",
           data:{
               MainList:"<?php echo json_encode($parentArray); ?>",
               Counter:counter,
           }, 
           success: function(result){
            $("#callMe").html(result);
        }});
        counter++;
     });
   });
</script>

ChangeQuestionProcess.php

<?php
  $index=$_POST["Counter"]; 
  $test[]=$_POST["MainList"];
  echo test[$index];
?>

在您的ChangeQuestionProcess.php ,此行:

$test[]=$_POST["MainList"];

...说“获取$_POST["MainList"] ,并将其作为数组$test的下一个元素”

您在第一个脚本的顶部正在执行类似的操作-我认为您的意思是这样,变量名后没有[]:

<?php  
  $childArray1=[1,'Question 1','Option 1A','option 1B','option 1C'];
  $childArray2=[2,'Question 2','Option 2A','option 2B','option 2C'];
  $parentArray=[$childArray1,$childArray2];
?>

您甚至可以简化为:

<?php
  $parentArray = [
    [1,'Question 1','Option 1A','option 1B','option 1C'],
    [2,'Question 2','Option 2A','option 2B','option 2C']
  ];
?>

现在再次回到ChangeQuestionProcess.php记住, $_POST["MainList"]将是一个包含JSON编码数据的string (这就是json_encode()返回的内容)

因此,我认为您要尝试将JSON 解码数据数组读入$test ,您可以这样做:

$test = json_decode( $_POST["MainList"] );

最后,在回显变量时缺少$。 但是由于$test[$index]是一个数组,因此您只会在屏幕上看到Array而不是它的内容。 我认为您需要像print_r而不是echo东西:

<?php
  $index = $_POST["Counter"]; 
  $test = json_decode( $_POST["MainList"] );
  print_r( $test[$index] );
?>

暂无
暂无

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

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