I have a json object in a PHP file and I want to access it from a JQuery.js file, which both located in an index.php page.
Do you have an idea how to开发者_JAVA技巧 do that ?
index.php
<?php
include('theFileThatContainsJson.php'); // say it's $json
?>
<html>
<head>
<script language="javascript" src="jquery.js" type="text/javascript"></script>
</head>
<body>
.............
</body>
</html>
and here, what we have in jquery.js file, you can see my work (which doesn't work ;) ):
$.getJSON(<?php echo '$json'; ?>, function(data){ .... }
How to solve the puzzle <<< at least for me at this moment :) ?
One way (nasty!) would be to do something like this..
<script language="javascript" src="jquery.js.php?data=<?php echo base64_encode($json) ?>" type="text/javascript"></script>
.. and on your jquery.js.php
file:
$.getJSON(<?php echo base64_decode($_GET['data']) ?>, function(data) { ... });
Of course, this is terrible practice and shouldn't really be done.. The best ways could include:
- Have
theFileThatContainsJson.php
to simplyecho
the JSON, and havejquery.js
just do an AJAX request to get the data - Have
theFileThatContainsJson.php
actually print out a<script></script>
tag that contains a Javascript variable which you can use
if json not big:
$.getJSON('<?php echo '$json'; ?>', function(data){ .... }
or even
$.getJSON('<?php include('theFileThatContainsJson.php'); ?>', function(data){ .... }
in second case theFileThatContainsJson.php should echo that json. in both cases should be in body of page
anyway I would not suggest to make it like that (use ajax for example)
精彩评论