簡體   English   中英

使用ajax()或jQuery.getJSON和jquery將php arrray對象傳遞給外部javascript文件?

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

這已被問了很多,但我有點不能單獨做,新的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 = Please相同,幫我修復代碼,請發布代碼示例。我不介意我使用$ .ajax()獲得答案也回答。未來可能會有所幫助:)

我懷疑它與異步加載有關。 我將在getJSON調用中定義Sets變量:

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

(在此處查看類似問題: jquery中的持久性.getJSON()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM