1

我这样做正确吗?据我了解,如果我在调用 print_r 时将“返回”值定义为 true,它应该返回一个字符串。我有以下功能:

function alert($string) {
    echo '<script>alert("' . $string . '");</script>';
}

当我向该函数传递一个常规的旧引号封装字符串时,它工作得很好而且花花公子,但是当我输入它时:

alert(print_r($array,true));

什么都没有发生,我没有看到错误,但回显 print_r($array,true) 有效。感谢您提供的任何帮助,我只是想了解这里出了什么问题,即使这显然是一个非常小的问题。

4

3 回答 3

2

采用

<script>
    alert(<?php echo json_encode(print_r($array, true)); ?>);
</script>

反而。注意使用 json_encode - 这是为了防止任何'或其他 JS 元字符引入 JS 语法错误,例如:

<?php
$name = "Miles O'Brien"; // note the '-quote in there
?>

<script>
alert('<?php echo $name ?>');
</script>

会给你:

alert('Miles O'Brien');
      ^-- start of string
              ^--end of string
               ^^^^-- unknown variable/function.
于 2013-09-23T17:57:08.967 回答
1

Your alert function has two problems handaling that input. first, as metioned, your JS is missing qutes. Second, the new lines should be converted to the string '\n'. otherwise your call to the alert function (in the js) will end in another line, which is not correct. for example:

    alert("hello
    world");

is invalid syntax.

so, this alert function will probably work:

    function alert($string) {
        $string=preg_replace('/\n/m','\\n',$string);
        echo '<script>alert("' . $string . '");</script>';
    }
于 2013-09-23T18:10:46.803 回答
0

print_r (as well as var_dump) outputs its content to stdout. However, you can control this behaviour with PHP's buffers.

Have a look at What is output buffering?, then http://www.php.net/manual/en/ref.outcontrol.php.

于 2013-09-23T18:00:26.567 回答