简体   繁体   中英

Why is my Javascript alert not being displayed?

Basically, I am trying to call a Javascript alert via PHP. Although, the alert does not work at all.

This is my echo statement that dynamically creates the alert

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

I found that if I change the alert to this, it works perfectly:

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

I believe there is a problem with the linebreaks.

I changed my code to this, yet still no luck:

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

I am getting an error of:

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)

Does anyone have any suggestions to why this is not working? Searched online far and wide and could not find a solution.

Thanks in advance!

Your \\n characters are being replaced by literal line breaks by PHP.

Am unescaped literal line break inside a string literal is an error in JavaScript.

Use \\\\n to send a line break escape sequence to JavaScript.

Try something like that:

    <?
    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>";
    ?>

为了增加昆汀的答案,将单引号和双引号切换也能解决问题吗?

Put one space between \\n and next character and it will work. I tried that for your code on my system and it worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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