简体   繁体   English

将服务器返回的字符串分配给javascript字符串最简单的方法是什么?

[英]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.

相关问题 从 php 到 jquery/ajax 中获取回显或返回字符串的最简单方法是什么 - What is the easiest way to get an echoed or returned string from php into jquery/ajax 给定一个表示XML文件的字符串,用Javascript或jQuery查找所有名称空间声明的最简单方法是什么? - Given a string representing an XML file, what's the easiest way to locate all namespace declarations with Javascript or jQuery? 在javascript中本地化字符串的最简单方法 - Easiest way to localize string in javascript 使用javascript读取/操作查询字符串参数的最简单方法是什么? - What is the easiest way to read/manipulate query string params using javascript? 基于javascript中的模板来选择字符串部分的最简单方法是什么 - What is the easiest way to pick portions of a string based on a template in javascript 在字符串中短划线后大写字母最简单的方法是什么? - What's the easiest way to capitalize letters after dash in a string? 从对象数组创建字符串的最简单方法 - Easiest way to create a string from an array of objects 从 Javascript 中另一个字符串的开头删除一个字符串的最快方法是什么? - What's the fastest way to remove a string from the beginning of another string in Javascript? 阻止在JavaScript中每X秒调用一次函数的最简单方法是什么? - What's the easiest way to stop a function from being called every X seconds in JavaScript? 在Javascript Web脚本和Erlang服务器之间进行通信的最简单方法是什么 - What is the easiest way to communicate between Javascript web script to an Erlang server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM