简体   繁体   中英

What's the easiest way to assign a string returned from the server to a javascript string?

The following does not work:

var js_str= '<?php echo $str_from_server; ?>';

The problem is that, $str_from_server can contain any characters. If it contains single quotes or line breaks or others, the above code will break. And I do not have access to the server-side code. What's the easiest way to "escape" the contents of $str_from_server into a javascript string, and then it can be restored later?

Since you are echoing that variable to your JavaScript code directly, you could use the json_encode function:

var js_str = <?php echo json_encode($str_from_server); ?>;

It will safely escape quotes for you, eg:

<?
  $str ='"\'"\'"\'"';
  echo  json_encode($str); // "\"'\"'\"'\""

I would do:

var js_str= '<?= addslashes($str_from_server); ?>';

or:

var js_str= '<?= str_replace("'", "\'", $str_from_server); ?>';

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