简体   繁体   中英

Pass php arrray of objects to external javascript file with ajax() OR jQuery.getJSON and jquery?

This has been asked a lot, but I kind of cant do it alone, new to php and mediocre with jquery. So, this is my php file

<?

            include("dbinfo.inc.php");

mysql_connect($host,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query="SELECT ID, NAME FROM sets";
$result=mysql_query($query);

 while ( $results[] = mysql_fetch_object ( $result ) );
     array_pop ( $results );

$cards = json_encode($results);


echo $cards;
mysql_close();

?> 

This is the way the resulting json looks :

[{"ID":"1","NAME":"Abundant Growth"},{"ID":"2","NAME":"Aggravate"},{"ID":"3","NAME":"Alchemist's Apprentice"},{"ID":"4","NAME":"Alchemist's Refuge"},{"ID":"5","NAME":"Amass the Components"},....

For one reason or another, I would like to have my js code in separate js file. I try to access the data with this code:

var Sets = new Array();

 jQuery.getJSON("php/mainDB.php", function(data) {
Sets=data
    })

and I hope that Sets will be defined as an array of objects ( the same thing I get with Sets = Please, help me fix my code, and please post code example. I wont mind if I get an answer using $.ajax() answer, too. Might be helpful in the future :)

I suspect it has to do with asynchronous loading. I would define the Sets variable within the getJSON call:

jQuery.getJSON("php/mainDB.php", function(data) {
var Sets = new Array();
Sets=data;
alert(Sets[0].NAME);
})

(See a similar issue here: Persistence within jquery .getJSON() )

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