[英]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. 问题是$ str_from_server可以包含任何字符。 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?
将$ str_from_server的内容“转义”为javascript字符串,然后可以在以后还原的最简单方法是什么?
Since you are echoing that variable to your JavaScript code directly, you could use the json_encode
function: 由于您直接将该变量回显到JavaScript代码,因此可以使用
json_encode
函数:
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); ?>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.