开发者

Shared JSON data for php and Javascript/Ajax

I am writing a validation mechanizm for my website. Some code is used with Javascr开发者_如何学Goipt and ajax to validate (mostly lengths of) strings. And some other code is used in php on the server side.

Both PHP and Javascript need to use the same vars, say MAX_USERNAME_LENGTH. So that they stay in sync, and save on development time up front.

I was thinking of using JSON. But after researhing a little I noticed that:

$.getJSON("http://myurl.com/vars.json", function(json) {
  alert(json['MAX_USERNAME_LENGTH']);
})

for starters, this for some reason won't access a local location as ../includes/vars.json, and returns 404 for some reason....

  1. I was thinking, if I put this in the $(document).ready(function () then all the code would run, but the vars themselves would not have loaded if the network was slow....

Is there a way to simply do something like :

var json=parseJsonFromLocalFile("../includes/vars.json");

I need this also for the php, but there I think it would be easier using json_decode() Thanks in advance!!!


You could create a Javascript file instead of a JSON one - just define all your variables in a PHP array, then make a PHP file with contents like:

var config = <?php echo json_encode($config); ?>;

and load it like:

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

(vars.js would be a better name, but would require that your server knew to process *.js files as PHP.)

This will load your variables synchronously, and gets them into the global scope more easily than an asynchronous JSON load.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜