0

这已经被问了很多,但我有点不能单独做,php新手和jquery平庸。所以,这是我的 php 文件

<?

            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();

?> 

这是生成的 json 的样子:

[{"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"},....

出于某种原因,我想将我的 js 代码放在单独的 js 文件中。我尝试使用以下代码访问数据:

var Sets = new Array();

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

我希望 Sets 将被定义为一个对象数组(与 Sets 得到的相同=请帮我修复我的代码,并请发布代码示例。我不介意使用 $.ajax() 得到答案也回答。将来可能会有所帮助:)

4

1 回答 1

2

我怀疑它与异步加载有关。我会在 getJSON 调用中定义 Sets 变量:

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

(在此处查看类似问题:jquery .getJSON() 中的持久性

于 2013-07-29T17:59:55.557 回答