简体   繁体   English

将变量和数据从PHP传递到JavaScript?

[英]Pass variables and data from PHP to JavaScript?

This is not a duplicate of How to pass variables and data from PHP to JavaScript? 这不是如何将变量和数据从PHP传递到JavaScript的副本

After consulting the previous question, I have another : 在咨询了上一个问题之后,我还有另一个问题:

My problem is that when I get the php array in Js, and I print it, I have just [object][object] 我的问题是,当我在Js中获得php数组并打印时,我只有[object] [object]

<?php 
    $tl = array(
         0=>array('a', 'b', 1),
         1=>array('c', 'd', 2)
    ); 
?>

and javascript : 和javascript:

<script type="text/javascript">
    var arr= <?php echo json_encode($tl ); ?>;

    for(var i=0;i<3;i++){
        alert(arr[i]);
    }
</script>

You should display it using console.log instead of alert : 您应该使用console.log而不是alert显示它:

console.log(arr[i]); //Check the result in you browser console

console.log : Formats your objects nicely and allows to traverse them. console.log:很好地格式化对象并允许遍历它们。

Hope this helps. 希望这可以帮助。

Remember : You don't have more than 2 object in your array so you should not run loop more than 2 times. 切记 :数组中的对象不超过2个,因此循环运行不应超过2次。 first loop give you permission to access the object of array then you can run a loop to show/get the property of object. 第一个循环授予您访问数组对象的权限,然后您可以运行一个循环以显示/获取对象的属性。

 <?php 
   $tl = array(
      0=>array('a', 'b', 1),
      1=>array('c', 'd', 2)
  ); 
?>

var arr = ; var arr =;

for(var i=0;i<2;i++){
    for(var j=0;j<3;j++){
        alert(arr[i][j]);
        console.log(arr[i][j]);// you can also show the value from the console of your browser
  }
}

output of console 控制台的输出

在此处输入图片说明

Try this ;) 尝试这个 ;)

alert() shows type if not basic data type. alert()如果不是基本数据类型,则显示类型。 In your case it's Object that's why it's showing [object][object] 在您的情况下,正是Object才显示[object] [object]

To debug JavaScript one should use console.log() and other console methods like: 要调试JavaScript,应使用console.log()和其他控制台方法,例如:

console.log();
console.debug();
console.warn();
console.error();

etc. 等等

One more thing here you are trying to access values of nested array so you can go with alert like this: 在这里,您还要尝试访问嵌套数组的值,以便可以像这样使用alert:

var arr= <?php echo json_encode($tl ); ?>;
for(var i=0;i<3;i++){
    alert(arr[i][0] + " " + arr[i][1] + " " + arr[i][2]);
}    

OR 要么

Use nested loop to iterate inner array values; 使用嵌套循环来迭代内部数组的值;

try this: 尝试这个:

<input type="hidden" id="array" value="<?php echo json_encode($tl); ?>" /> 

then use 然后使用

<script type="text/javascript">
var arr = getElementById('array').value
for(var i=0;i<3;i++){
    alert(arr[i]);
}
</script>

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

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