开发者

Clean php output into javascript

Due to the nature of my project. I am pulling data from my db and outputting to javascript. Thi开发者_JAVA百科ngs were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.


If all you have is a single string value then see answer by Tomalak Geret'kal.

If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:

<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>

you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.

Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.


You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.


You should be encoding that data into json. PHP has a handy function to do this, json_encode.

Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.

Read this: http://php.net/manual/en/function.json-encode.php

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜