简体   繁体   中英

Unterminated string literal with PHP in JavaScript

Please tell me why this code tells me

SyntaxError: unterminated string literal

My code:

<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo $geladen; ?> ");

</script>

That's a JavaScript error message, which strongly implies one of two things:

  1. the JavaScript that reaches the browser still includes the <?php etc., meaning the PHP didn't get parsed on the server (and thus the browser flipped out on "./testtext" ), or

  2. the file testtext (and therefore your variable $geladen ) contains quotation marks. Either is possible from the very little information you have posted.

You can figure out which it is by looking at the HTML in your browser.

If it's the former (if you see <?php in the HTML), then you need to fix your server configuration.

If it's the latter (if testtext contains any " marks), then you need to encode it properly before echoing, using json_encode() like this:

<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo json_encode($geladen); ?> ");

</script>

All that said, mixing PHP and HTML (not to mention PHP, HTML, and JavaScript ) this way is not a great practice. You'd be much better off using a templating engine of some sort (Twig, Blade, etc.).

If the contents of 'testtext' contains a quote mark, it will break the javascript. Try addslashes().

<script>
console.log(" <?php $geladen = addslashes(file_get_contents("./testtext")); echo $geladen; ?> ");
</script>

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