开发者

What is the best practice to pass many server side information to JavaScript?

Let say that I have many Javascript inside pages. At this moment is pretty easy to initialize variabl开发者_如何学Goe by simply using some Print/Echo statement to initialize JavaScript value.

Example: var x = <?php echo('This is a value');?>

I first thought that I could pass all variables value by parameter of function BUT it's impossible because we have a lot of values (we have a multilanguage website and all text are from the server (BD)).

Example : initializeValues(<?php echo('Value1,Value2,Value3,Value...');?>);//JS Method that can be external of the page

More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file. What would be the good way to initialize all those variables? If I bind the JavaScript methods by using OnLoad of the document I won't be able to use Print/Echo method to populate all values.

Any good pattern to resolve this task?


A very popular pattern is the use of the JSON format. There are libraries to produce it, and Javascript directly consumes it.


With php you can create an associative array then using json_encode you can serialize it for output on the page between some script tags.

for some examples on doing that you can look at http://www.php.net/manual/en/function.json-encode.php


Here's how I do it:


<?php

$foo = array('bar' => 'gork');

?>
<input id='foo' type='hidden' value='<?= json_encode($foo); ?>' />

Then client side (I'm using Prototype) :


var foo = $F('foo').jsonParse();
alert(foo.bar);


var x = <?php echo('This is a value');?>

Er, no, that would end up as:

var x = This is a value

(syntax error.) You want:

var x = <?php echo json_encode('This is a value', JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT);?>

The HEX_TAG escaping in PHP 5.3 avoids problems with the </ sequence appearing in a <script> block. The AMP and QUOT encoding is needed to ensure there are no problem " and & characters when you're putting code in an attribute value delimited by " or a non-CDATA XHTML script block. If you're only ever using a HTML script block (or XHTML CDATA script block) you can get away without them (although they do no harm either).

json_encode will also happily encode an array of values to put in a JS variable, not just a string.

More problem come when we want to take off all JavaScript from pages to move everything on external JavaScript file.

It's a good idea to put all your static code, including code that binds onto event listeners, in an external JavaScript file. However per-page data should still stay on the page, either in appropriate attributes of the document itself (eg. class names for unobtrusive scripting) or in a simple <script type="text/javascript">var data= ...;</script> block with no other code.


best practice? passing values from server to the client-side js is too volatile for a singular best practice.

let's say you use Smarty. then, my best practice is:

<script type="text/javascript">
var limit = Number("{$limit}");
var msg = "{$msg}";

{literal}
// code using the variables
{/literal}
</script>

but I can also see this as a very sensible approach:

function to_js_vars(arrray $jsvars)
{
    foreach ($jsvars as $name => $info) {
        printf(
            "var %s = %s("%s");\n"
          , $name
          , $info['type']
          , $info['val']
        );
    }
}

where $info['type'] is one of Number, Boolean, and '' (empty string) for everything else

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜