如何在警告消息框中显示print_r()内容?

时间:2013-05-15 22:51:58

标签: php javascript alertdialog

我知道每当我写

$food = array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat');
$text = print_r($food, true);
echo $text;

输出将是:

  

数组('fruit'=>'apple','veggie'=>'番茄','面包'=>'小麦')

但是当我试图通过警告消息框显示它时,它没有显示任何内容。
我编写的js alert代码如下:

echo "<script type='text/javascript'> alert('{$text}') </script>"; 

这不起作用。当我为$ text分配不同的字符串时,它就可以工作了。似乎alert()不喜欢$ test string的格式。 如果我这样写:

echo "<script type='text/javascript'> alert('Array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat')') </script>";

我得到了正确的输出。所以不确定那里有什么问题。

1 个答案:

答案 0 :(得分:5)

要将PHP数组转换为javascript数组,必须使用json_encode。 JSON(JavaScript Object Notation)是一种基于JavaScript的编程语言之间数据交换的格式。由于JSON是文本格式,因此编码结果可以用作字符串或javascript对象。

$food = array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat');

// show the array as string representation of javascript object
echo "<script type='text/javascript'> alert('".json_encode($food)."') </script>";

// show the array as javascript object
echo "<script type='text/javascript'> alert(".json_encode($food).") </script>";

// show the output of print_r function as a string
$text = print_r($food, true);
echo "<script type='text/javascript'> alert(".json_encode($text).") </script>";

一些调试技巧:

  • 用于检查JavaScript对象,console.log是非常有用的
  • 如果您想要更清晰的print_r输出(在Windows上),请使用:

    function print_r2($val){
        echo '<pre>'.print_r($val, true).'</pre>';
    }
    
相关问题