开发者

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 n开发者_如何学JAVAot 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, e.g.:

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


I would do:

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

or:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜