2013-09-30 44 views
1

我使用ZendFramework,我需要填充數據存儲在數據庫中的表 視圖,但我需要使用Ajax和json 我有一個web服務,打印以下在zend中使用ajax來填充數據庫中的視圖

{"cat":[{"id":"1","name":"Meat","image_url":"meat.jpg"}, 
{"id":"2","name":"Soup","image_url":"soup.jpg"}, 
{"id":"3","name":"drink","image_url":"drink.jpg"}, 
{"id":"8","name":"Pastries","image_url":"Pastries.jpg"}, 
{"id":"9","name":"Ice-cream","image_url":"ice_cream.jpg"}, 
{"id":"10","name":"salad","image_url":"salad.jpg"}]} 

的URL,該Web服務是

http://localhost/resturant/public/categories/show-categories 

我如何使用這個Web服務和Ajax填充表 我很begineer在阿賈克斯實際數據和我搜索谷歌,但斯蒂爾升陷 請任何想法 thnxx所有

回答

1

您可以使用jQuery的$.getJSON功能:

http://api.jquery.com/jQuery.getJSON/ 

爲了填補使用$.getJSON表如下:

$.getJSON("http://localhost/resturant/public/categories/show-categories", function(cat) { 
    var categories = cat.cat; 
    //Iterate throught the array 
    for (var i=0;i<categories.length;i++) 
    { 
    category = categories[i]; 
    //Append the category to the table using the format you want 
    $("#mytable").append("<tr><td>"+category.id+"</td><td>"+category.name+"</td></tr>"); 
    } 

}) 
+0

thnxx很多它的工作:) –

+0

當我寫 警報(貓);它顯示json字符串 ,但是當我寫alert(cat.cat)時,它顯示undefined 我也嘗試 alert(cat [0] .cat) 和alert(cat.cat [0]),但也顯示undefined –

+0

它是因爲在我的答案中,我應該使用'$ .getJSON'而不是'$ .get'。 jQuery將響應解析爲字符串,而不是將其解析爲JSON。 –

1

我認爲JS不應該產生HTML(如果可能的話)。好的做法是創建separated action,這將返回HTML。在此操作中,您將調用您的API方法,並在View中生成您的表格。在JS中,你只能對新動作發出Ajax請求(並將dataType: 'html'傳遞給ajax設置對象)。

相關問題