开发者

Loading JS configuration from server?

I want my JS to load certain information that needs to come from the server. Examples would be URLs, language specific messages, etc. What is the best way to get this information from the server to the JS?

Right now, I have such v开发者_Go百科alues stored in an actual JS file. I don't like this approach because information is duplicated on the server side.

Would it be a good idea to have an initial JS to make an Ajax request to get all these details? Perhaps store this in a global variable so that it is accessible from anywhere? (A benefit of my current approach is that I don't need to necessarily set such information as a global variable; I could, for example, hard code and alert message where it is needed).

Any advice on best practice for my situation?


As you already use PHP, why not use that to generate a dynamic .js file that contains all your variables and include that on the page?

PHP:

var foo = '<?php echo $foo; ?>';
var bar = '<?php echo $bar; ?>';

HTML:

<script type="text/javascript" src="vars.php"></script>
<script type="text/javascript" src="actual_javascript_stuff.js"></script>
...

This way you can keep all your config in one place. You can include the PHP's config file and populate the JavaScript variables using that.


You could use ajax sure, but if you don't use ajax to anything else a simple solution is to add an extra <script type="text/javascript" src="config.php"></script> and have that file auto generate JS settings.


Rename the file that contains all your configuration to filename.js.php, this tells the server that it needs to parse the file before it is served.

Then use php expressions to get your values, for example:

var username='<?=$username;?>';

(By the way <?=...;?> is the shorthand for <?php echo $username; ?>)

Another way of going about it, have all the properties that you want to pass to the front end in a PHP object, and pass it as a json string.

So initially, in filename.js.php, have something like:

var properties = <?=json_encode($php_properties_object);?>

Then when the language is sent on the client, simply return that same json encoded object to your front end through an AJAX query and assign it to the properties javascript variable. Then get the javascript code to reload all the config of off that.


This might be helpful: http://www.gifnoc.com/config (if it does JSON I suppose)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜