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

江枫思渺然 提交于 2019-12-17 10:59:25

问题


In my application I rely heavily on JavaScript to enhance the user interface, but all of the data comes from a database and is processed by PHP. By default I use 'echo' statements to substitute the required values "just in time" like so:

var myVariable = <?php echo $myVariableInPHP ?>

This, however, does not strike me as very elegant and I am concerned about stability and maintainability of such code.

Do I have any alternatives here?

For server-side, I am using the Symfony 1.4 PHP framework.

Thanks,


回答1:


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).




回答2:


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>';



回答3:


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




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/3613186/what-is-the-safest-way-of-passing-arguments-from-server-side-php-to-client-side

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