开发者

What are common methods of sending initial configuration variables to an Ajax client on the page load?

A complex web-app can have a large amount of user and/or context specific meta and configuration information. eg, user's preferred result-se开发者_如何学JAVAt size, timezone, beginning of the week (Sun/Mon), etc.

What are the possible ways to transport the variables to the client application as it is loading (hidden variables? JSON embedded somewhere?), and what are the pros/cons of each method?

I know of a few ways to hack things together, but I'm curious if anyone has identified good design patterns to use, or best practices they can share.

Although I'd prefer general info on this, my primary stack is jLAMP (jQuery, Apache, MySQL, PHP)

EDIT: I already have applications that do this, so I'm not looking for a quick fix, or suggestions for an entirely different paradigm (as in, not loading config). I'm looking for a discussion with the options and pros/cons of each, so that I might tune what I have, or a new user would be presented with plenty of options to make a good design decision from the start. Thanks!


As others have pointed out, if there is a lot of information to transport during the loading of your application I would not recommend using AJAX, since you're putting an overhead on your connection.

My chosen method would be to render all the configuration information on the head tag of your application, using PHP, that way, once your events get triggered (after the DOM has finished loading I would assume), you have all the information at your disposal.

Code example:

<head>
<script type="text/javascript">
 //Some js code here....
  var myConfigurationName = "<?=$myConfigurationNameFromDatabase;?>";
 //Some more js code here...
</script>
</head>

The way you format your configuration data is completely up to you, it all depends on how related all of it is, or in how many different places / objects / functions you might need to use it.

You could create some different configuration objects depending on your data, or only one that concentrates all of them. It really depends on the application design you have so far.

If you have a strong OO design on your JS code, you could check out this site and see if any of the basic patterns match your needs.

Feel free to elaborate a bit more on your design (if you can) to help us understand where you stand and how we can help you.

Happy coding!


For me it's passing in a JSON array. It's so flexible on the client side I'm not sure why you wouldn't use it. On the backend I build it up using a regular PHP array and then just convert it to JSON using json_encode before echoing to the webpage.

<script>var myObject = <?=$mySettings?></script>

and you're good to go. As a bonus I just convert the json object to a string before I pass it back to PHP using a single variable in a post and convert it back to a PHP array for manipulation and inclusion into a database.


So far I use a php file to store custom setting for my application. Then include them in a page as I need them. Don't forget to set content type to "text/javascript"

As illustration, my configuration file will look like:

<?php header('Content-type: text/javascript'); ?>

var myApp = {
    // setTimeOut id
    timeoutID : null,

    // Cards clearance delay
    cardsClearanceDelay : 1500,

    // Add other attribute as needed
}

And include them in the page

<html>
    <head>
        <script type="text/javascript" src="web/get_configuration"></script>
    </head>

I build my application using CI, web/get_configuration just calling controller action to render my javascript configuration file.


Have you ever tried jQuery taconite .

http://jquery.malsup.com/taconite/

JSON is a great data exchange format. But it's not the best solution for every problem.

In comparison, the Taconite model only requires that the server return valid XHTML. There is no coding required on the client at all!


First you need to figure out what is more important for you - fine tuning server preference, user side performance, modularity, or something else.

So you could load configuration for each module in some separate way with a separate class or even hardcode some stuff in JS. You would gain agility but it would be an overall mess, but it might be a mostly working mess. Probably depends on how isolated the coding teams or developers of modules are.

Instead of spreading configuration across modules you could separate different kinds of configuration:

  1. Some temporary configuration can be stored in localStorage (or similar, even cookies) and you will gain from adding events that can push the configuration to all open tabs. Of course this would be great only when one user has only one computer, but you could still allow to save this configuration to your server.
  2. User preferences might be put in one serialized object (JSON is pretty light) and sent with AJAX calls. You could cache this settings on PHP side after user would change them and simply serialize key-value pairs.
  3. Site-wide configuration should probably be made separate as it would rarely changed and could be stored in a JS file. You want to load it after page load? Fine - you can do that to with AJAX and then run eval. What would you gain? You could also load the same JS file statically and it would be cached by the browser and not loaded every time and wouldn't be touched by PHP interpreter at all.

And you could mix all this as it mostly happens in most cases of big websites I've seen.

As for the format I would prefer JSON. It's pretty light (especially when comparing to XML) and you can GZIP it nicely to make it even lighter. JSON is also easily extend-able over time (you can add and remove options without fatal failures) and is almost JS native.

As to how generate JSON... Well CACHE IT. Beside some specific things preferences most of the configuration options won't change too often (not as often as being read).

Also note that configuration may be understood in many ways - in MediaWiki/Wikipedia you can add your own JavaScript.

Also you may want to express more options then it is needed if you want your users to create some extra scripts.


Simple persistent user selected options are probably best set by cookies. Everything more complex is better handled by json values.

Obviously you could put custom javascript code into your header to set js variables, but this requires you to render code dynamically, which is (IMHO) ugly and error prone. On the other hand you can render custom meta tags holding all your custom data, and read it out by javascript later.

My simple and elegant solution in the past was to just render json in a script tag in the header

<script id="initparams" type="application/json"> 
    [ output of json.dumps({a: "AAA", ....}) ]  
</script>

And later in a jQuery document ready handler (which may be loaded from an external file):

var initparams = $.parseJSON($('#initparams').html());

Since I use json dump and parse on both sides no chance for wrong escaping or an injection attack.

I've done the same embedding json params in <div class="options"> for options belonging to a jstree or data table, when I needed just a few local parameters not warranting an AJAX call. You can either hide the div.options by CSS, or remove it from the dom when parsing it:

var tableoptions = $.parseJSON($('table.mydata > div.options').remove().html());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜