2011-03-08 72 views
0

我有一個JavaScript聯繫一個PHP頁面,它從數據庫獲取一些數據並將其保存在一個數組中。數組從php到jquery通過ajax

我想採取該數組並使用jquery進行循環。

數組是這樣的:

Array ( 
    [0] => Array ([image] => article_list1.png [title] => Everyone involved in OMS in Ghent) 
    [1] => Array ([image] => article_list1.png [title] => Everyone involved in OMS in Ghent) 
    [2] => Array ([image] => article_list1.png [title] => Everyone involved in OMS in Ghent) 
    [3] => Array ([image] => article_list1.png [title] => Everyone involved in OMS in Ghent) 
    [4] => Array ([image] => article_list1.png [title] => Everyone involved in OMS in Ghent) 
    [5] => Array ([image] => article_list1.png [title] => Everyone involved in OMS in Ghent) 
); 
+0

我會簡單地轉換數組到JSON和發送JSON字符串到客戶端。我認爲jQuery可以在沒有擴展名的情況下反序列化JSON。 – Wukerplank

回答

2

做到這一點,最好的辦法是json_encode數組,然後呼應結果出來的JavaScript/jQuery的:

json_encode PHP function

這裏是PHP php demo

<?php 
$myarray = Array ( 
    Array ('image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent'), 
    Array ('image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent'), 
    Array ('image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent'), 
    Array ('image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent'), 
    Array ('image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent'), 
    Array ('image' => 'article_list1.png', 'title' => 'Everyone involved in OMS in Ghent') 
); 

echo json_encode($myarray); 
?> 

這應該給你這樣的事情:

[{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"}] 

並使用jQuery jsfiddle demo訪問:

var myJson = '[{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"},{"image":"article_list1.png","title":"Everyone involved in OMS in Ghent"}]'; 
myJson = JSON.parse(myJson); 
for(var i=0; i<myJson.length; i++) 
    console.log(myJson[i].image+ ' ' + myJson[i].title); 
+0

K.我怎麼把它變成jquery中的數組? – Patrik

+0

@Patrik看看演示並更新 – kjy112

+0

AAh,太棒了!謝啦! – Patrik

0

你總是可以使用PHP來打印數組作爲一個js列表。或者通過json導出它。