What is the safest way of passing arguments from server-side PHP to client-side JavaScript [duplicate]

♀尐吖头ヾ 提交于 2019-11-27 13:55:41

My favorite way is :

<?php

$var = array(
  'prop1' => 'value1',
  'prop2' => 'value2',
  // ...
);

?>
<script type="text/javascript">
   var varNameSpace = <?php echo json_encode($var); ?>;

   alert( varNameSpace.prop1 ); // -> 'value1'
</script>

Using json_encode() ensures that the values passed to Javascript are escaped and well formatted. Using a common variable container also prevents from over using the global space (window).

You might want to use JSON for this, it's really simple to use in both PHP (check json_encode()) and JavaScript.

It's safe to use within <script>-Tags and browsers which understand JavaScript. Note that the PHP function doesn't encode < and >.

Some example PHP:

$user = (object) array("name"=>"Joseph", "age"=>29, "email"=>"asdf@example.net");
echo '<script type="text/javascript"> var user = '.json_encode($user).'; </script>';

I'd try to use JSON. Here is a link for you to php.net explaining how to do this.

http://php.net/manual/en/book.json.php

First of your solution does work, but It is not a good practice to mix client-side code with server-side code. It is a best practice to put javascript in seperate .js files(no PHP in it)

I would first create an API(write documentation) like for example

GET
http://localhost/getProfile?username=$username

POST
http://localhost/getProfile/$username

It will return JSON-object using json_encode. You could use json-p for cross domain communication. Then from for example Jquery you can easily get the data.

This way your javascript would stay clean.

I prefer use_dynamic_javascript() helper. "Bad" thing about it is you have to think a bit more on splitting rendering template itself and config for it into separate requests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!