php和Javascript/Ajax的共享JSON数据 [英] Shared JSON data for php and Javascript/Ajax

查看:118
本文介绍了php和Javascript/Ajax的共享JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的网站编写验证机制.一些代码与Javascript和Ajax一起使用以验证字符串(大部分为字符串的长度).并且在服务器端的php中使用了其他一些代码.

I am writing a validation mechanizm for my website. Some code is used with Javascript and ajax to validate (mostly lengths of) strings. And some other code is used in php on the server side.

PHP和Javascript都需要使用相同的变量,例如MAX_USERNAME_LENGTH. 这样他们就可以保持同步,并节省开发时间.

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.

我当时正在考虑使用JSON. 但是,在重新研究了一点之后,我注意到了:

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']);
})

对于初学者来说,由于某种原因,它不会以../includes/vars.json的身份访问本地位置,并由于某种原因而返回404 ....

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

  1. 我当时在想,如果将其放在$(document).ready(function ()中,则所有代码都将运行,但是如果网络运行缓慢,vars本身将不会加载.
  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");

我也需要php,但是我认为使用json_decode()会更容易 预先谢谢!!!

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

推荐答案

您可以创建一个Javascript文件而不是JSON文件-只需在PHP数组中定义所有变量,然后制作一个内容如下的PHP文件:

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); ?>;

并像这样加载它:

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

(vars.js是更好的名称,但要求您的服务器知道将* .js文件作为PHP处理.)

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

与异步JSON加载相比,这将同步加载变量,并使它们更容易进入全局范围.

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

这篇关于php和Javascript/Ajax的共享JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆