简体   繁体   中英

How do I retrieve a JSON encoded array printed inside a <div> from a JavaScript file?

I know that this question might have been asked like 100 times, but, believe me, I checked a lot for already asked questions and I could not find a proper answer for my case.

Basically what I would like to do is pass an array my PHP code is generating to a separate JavaScript file which will do something with it. Nothing new untill now, I suppose, so let me give you some clarification specific for my case. Let's say I am a bit ahead.

I found many answers that suggested to just pass the encoded version of my array echoing it out inside my PHP file and then retreiving it from the separate JavaScript file.

I was going to use this method but what I encountered is that I can't go for getJSON() method because I have my encoded array inside a PHP file that outputs something more that just that.

So my final question would be: How can I retrieve, from my separate JavaScript file, my json_encoded version of the array from my PHP file?

And note again that I have my array echoed inside a (occasionally made style="visibility:hidden" for the purpose of not showing it to the user).

Thanks in advance

EDIT: Ok thanks for the answers. Probably i wasnt clear enough with all the details.

My program is made up of, let's say, 3 files.

1)HTML file with a form and a submit button->action send the data to the php file i was mentioning.

<form name="foo" action="foo.php" method="GET">
<input type="text" name="footext"/>
<input type="submit" value="Send Data"/>

2)PHP file which get the data from the previous form, process it and ultimately create the array i have to take into consideration

something that uses the $_GET['footext'] and produces $array in the end and of course, as i metioned earlier I was trying to solve this with

echo "<div style=\"display:none\">" . json_encode($array) . "</div>";

3)JS file which does something else, or will do, considering that everything in thit script is based on what i retrieve from my php array.

here i prepared some functions and tested them with a static array but what i need is to, obviously, retrieve $array from the previous file and use it instead of a bogus one

There are two solutions for this problem. First is to put that array/json-encoding generation code in another PHP file and get it via AJAX (getJSON) separately. Second is to put the contents of the output in a pre-processed format for Jquery, hide it in an random element and get its contents via jQuery selector. The first one is more simple and elegant, I'd implement it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM