I need to create a variable storing dynamically generated HTML content. The html content in the String returned from PHP might have single or double quotes.
html_content=<?=$string;?>;
The string may have double quotes like this:
<span id="something">something else</span>
or single quotes like this:
<span id='something'>something else</span>
Then, how can I correctly save the string in javascript? I can't use single quotes or double quotes.
You could save that kind of string by modifying it on the server side before output, like this:
html_content = "<?=addslashes($string);?>"
The method addslashes($string)
would then escape any double quotes at runtime before feeding it to the JavaScript variable.
Well you could always use JavaScript's escape function to serialize your string before storing it. That'll work.
I think the bigger issue here, though, is that single quotes are actually not valid the way you're attempting to use them in your id attribute like that (per the HTML spec). It always has to be double quotes. If the code that that's coming from isn't under your control, then there's not much you can do, it's just broken; but if it is under your control, you should fix it too.
Use json_encode
to pass almost any variable from PHP to JavaScript.
html_content=<?=json_encode($string)?>;
In the case of a string, it will automatically add quotes and any necessary escaping.
来源:https://stackoverflow.com/questions/12414408/how-to-store-a-string-in-a-javascript-variable-that-has-single-quotes-and-double