如何在javascript中访问多维php数组?

问题描述:

The code is like this:

<SCRIPT LANGUAGE="JavaScript">
     function showReview(){
      //javascript stuff
         <?php
            $http="obj.href ='http://localhost/PROJECT1/thispage.php'"; 
               if (array_key_exists(0, $arr)){
            $http .= "+'&PQID={$arr[0]['ID']}'+
                     '&PQNo={$arr[0]['QNo']}'+
                     '&PNextSWF={$arr[0]['NextSWF']}';";
            }
            echo $http; 
           ?>

        }
</SCRIPT>

But I can't access $arr array. I tried to declare it global or use the $GLOBALS variable.

Show Review is called during onclick. $arr is set in the main php code. I tried just accessing the array in the main php code and passing the resulting string to the javascript which is the '?&PQID=ar&PQno=1...' part of the URL but it doesn't pass successfully. I tried passing the array itself to the javascript but js but I couldn't access the contents.

Add this to the JS-function:

var arr=<?php echo json_encode($arr); ?>;

The PHP-Array "$arr" should now be accessible to JS via "arr" inside the JS-function.

I guess you are trying something like this:

<?php
  //example array
  $arr=array(
    array('ID'=>'0','QNo'=>'q0','NextSWF'=>1),
    array('ID'=>'1','QNo'=>'q1','NextSWF'=>2),
    array('ID'=>'2','QNo'=>'q2','NextSWF'=>3),
  );
?>
<script type="text/javascript">
function showReview(nr)
{
  //make the array accessible to JS
  <?php echo 'var arr='.json_encode($arr);?>

  //some obj, don't no what it is in your case 
  var obj={};

  var href='http://localhost/PROJECT1/thispage.php';
  if(typeof arr[nr]!='undefined')
  {
    href+='?PQID='+arr[nr]['ID']+
          '&PQNo='+arr[nr]['QNo']+
          '&PNextSWF='+arr[nr]['NextSWF'];
  }
  else
  {
    alert('key['+nr+'] does not exist');
  }

  //check it
  alert(href);

  //assign it
  obj.href=href;
}


</script>
<b onclick="showReview(0)">0</b>-
<b onclick="showReview(1)">1</b>-
<b onclick="showReview(2)">2</b>-
<b onclick="showReview(3)">3</b>

Try this

<SCRIPT LANGUAGE="JavaScript">
     function showReview(){
      //javascript stuff
      var http = 
         <?php
            $http="obj.href ='http://localhost/PROJECT1/thispage.php'"; 
               if (array_key_exists(0, $arr)){
            $http .= "+'&PQID={$arr[0]['ID']}'+
                     '&PQNo={$arr[0]['QNo']}'+
                     '&PNextSWF={$arr[0]['NextSWF']}';";
            }
            echo $http; 
           ?>

        }
</SCRIPT>

PHP runs on the server, Javascript on the client - they can't see each other's variables at all really. Think of it this way - the PHP code just generates text. It might be Javascript, but as far as the PHP concerned, it's just text.

Basically, you need to use PHP to generate text which is valid Javascript for creating the same data structure on the client.