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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16576301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:11:28  来源:igfitidea点击:

How to show print_r() content in alert message box?

javascriptphpalert

提问by Brian

I know that whenever I write

我知道每当我写

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

Output will be:

输出将是:

Array('fruit'=>'apple', 'veggie'=>'tomato', 'bread'=>'wheat')

Array('水果'=>'苹果','蔬菜'=>'番茄','面包'=>'小麦')

But when I am trying to display this via alert message box, it does not show anything.
The code for js alert I wrote as follows:

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

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

This does not work. When I assign a different string to $text then it works. Seems like alert() does not like the format of $test string. If I write in this way:

这不起作用。当我为 $text 分配一个不同的字符串时,它就起作用了。似乎 alert() 不喜欢 $t​​est 字符串的格式。如果我这样写:

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

I get the correct output. So not sure what is wrong there.

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

回答by Danijel

To convert PHP array into javascript array you must use json_encode. JSON (JavaScript Object Notation) is a format for data-interchange between programming languages based on the JavaScript. Because JSON is a text format, the result of encoding can be used as a string or as a javascript object.

要将 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>";

A few tips for debugging:

调试的一些技巧:

  • for inspection of JavaScript objects, console.logis a very useful
  • if you want a cleaner print_routput ( on Windows) use:

    function print_r2($val){
        echo '<pre>'.print_r($val, true).'</pre>';
    }
    
  • 对于 JavaScript 对象的检查,console.log是一个非常有用的
  • 如果您想要更清晰的print_r输出(在 Windows 上),请使用:

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