开发者

accessing a PHP object (in another file) within a jquery code. Help

开发者 https://www.devze.com 2023-03-21 14:13 出处:网络
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.

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 simply echo the JSON, and have jquery.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)

0

精彩评论

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

关注公众号