简体   繁体   中英

Return an Array in PHP and Javascript AJAX

Section 1

I'm trying to return an Array from PHP (after having created the file using fwrite)

I include that file on my next .load method (inside a Div) the new PHP file contains an include 'somefile.php'; there is my array ... and I would simply try to collect from PHP and use it the array with JS....

I once saw something like this ...

$(function(){
alert('<?php for_each($array as $key => $value){
         echo $value;     // Just an example
}
?>')
});

I wrote this piece of code on the fly so there might be a few sytax errors;

This works fine using PHP inside JS ...

I'm not sure if I heard PHP loads first and then JS ? or was it the other way around ?

Section 2

How about using JS inside PHP ? for example ....

<?php

echo "var myArray = New Array();"
echo "myArray = ('Apple','Banana','Orange','Kiwis');"
echo "return myArray";

?>

and then being able to fetch the data strait with JS ?

<script type="text/javascript">
    for(i=0;i<myArray.length;i++){
       alert(myArray[i]);
</script>

So how easy can I manipulate both languages in regards to RETURNING the array for example so it could be used in the global scope?

using PHP in JS : In short, you can echo the values in JS codes, eg

window.location = '<?php echo $url; ?>';

using JS in PHP : You can use AJAX . post the values to a PHP script

PHP runs first, so you can use it to write JavaScript code, that will get run once the page has been processed by the browser.

This would build JavaScript code with an array from PHP:

<script>
var myArray = <?php echo json_encode(array('apple', 'orange', 'kiwi'); ?>;

myArray.forEach(alert)
</script>

The other way around, passing data from JavaScript to PHP, can only be accomplished with some form of AJAX.

The PHP runs on the server, so from Javascript's point-of-view (running in the client's browser) it's like the PHP was never even there.

You can easily pass the PHP array to Javascript using PHP's json_encode() function:

$yourPHPArray = array("blah","blah","blah");

echo "var theArray=" . json_encode($yourPHPArray) . ";";

echo "for(var i=0;i<theArray.length;i++)";
echo "{";
echo "     window.alert(theArray[i]);";
echo "}";

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