为什么我的Javascript警报没有显示?

时间:2013-08-23 14:18:39

标签: php javascript alert

基本上,我试图通过PHP调用Javascript警报。虽然,警报根本不起作用。

这是我的echo语句,动态创建警报

echo "<script>alert('Uploaded file was not in the correct format\n\nExample of the correct format:\nquestion1,answer1,answer2,answer3,answer4\n
question2,answer1,answer2,answer3,answer4\nquestion3,answer1,answer2,answer3,answer4')</script>";

我发现,如果我将警报更改为此,则效果非常好:

echo "<script>alert('Uploaded file was not in the correct format')</script>";

我认为路线有问题。

我将代码更改为此,但仍然没有运气:

echo "<script>alert('Uploaded file was not in the correct format\\nExample of the correct format:\\nquestion1,answer1,answer2,answer3,answer4\\n
question2,answer1,answer2,answer3,answer4\\nquestion3,answer1,answer2,answer3,answer4')</script>";

我收到错误:

SyntaxError: unterminated string literal
[Break On This Error]   

alert('Uploaded file was not in the correct format\nExample of the
------^

createplay.php (line 1, col 6)

有没有人对为什么这不起作用有任何建议?在线搜索范围广泛,无法找到解决方案。

提前致谢!

4 个答案:

答案 0 :(得分:2)

您的\n个字符被PHP的文字换行符替换。

字符串文字中未转义的文字换行是JavaScript中的错误。

使用\\n向JavaScript发送换行符转义序列。

答案 1 :(得分:1)

尝试类似的东西:

    <?
    echo "<script>alert('Uploaded file was not in the correct format\\n\\nExample of the correct format:\\nquestion1,answer1,answer2,answer3,answer4\\n
   question2,answer1,answer2,answer3,answer4\\nquestion3,answer1,answer2,answer3,answer4')</script>";
    ?>

答案 2 :(得分:1)

要添加到Quentin的答案,是否会切换单引号和双引号也能解决问题?

答案 3 :(得分:0)

在\ n和下一个字符之间放一个空格,它会起作用。我尝试在我的系统上使用你的代码并且它可以工作