Passing dynamic parametes to js code - which is better practice?
For passing dynamic values to js code, is it better to do like this?
var myVar = '<?php echo addslashes($_SESSION['myVar']); ?>';
Or make an AJAX call at run time to get the session variable and assign it to myVar?
What are the pros and cons?
I personally prefer the AJAX method. It makes the code look better in case of complex array assignments etc.
Would like to get expert opinions.
Updates
I understand that using the AJAX method, every http request counts. But if we have well defined functi开发者_StackOverflow社区ons inside the javascript files, we would only need to have the function parameters available. And the parameters can be passed in the function calls whenever we want to call them, e.g. like this:-
<a onclick="some_function('<?php echo $_SESSION['var'] ?>')">
This is how I normally do and in my project I rarely need to pass them inline in javascript files. And I have AJAX calls for doing server side processing (of course when it is needed).
The basic idea I have here is to have separate js files intead of inline js scripts. I was looking at this question. I would definitely not make an AJAX call for fetching each and every variable (as it may look like from my question) because such a situation would not arise.
Thanks.
An AJAX call is another request, and the results will not be immediately available - writing dynamic data inline is available straight away. In this case, I would tend to choose the inline approach.
PHP's json_encode()
might make it relatively easy to write out even huge arrays without cluttering the code much.
First, note that you are not actually generating Javascript code dynamically; You are using PHP to pass the value of an argument to the browser.
If this is the only (or the main) functionality of PHP in your code, it is better to use AJAX, and not generate the page itself using PHP (i.e., use a .html file instead of .php). Reason: Works faster, as most of the content is stored statically.
If you use PHP to generate most of the page, there is no need to add another request, as Pekka mentioned. Just inline it.
精彩评论