문제

I'm using ZendFramework and I need to populate the data I store in database in a table in the view but I need to do that using Ajax and json I have a web service that print the following

{"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"}]}

the url for this web service is

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

how can I using this web service and Ajax populate the data in Table I'm so begineer in Ajax actually and I search google but still stuck please any Idea thnxx all

도움이 되었습니까?

해결책

You can use jQuery's $.getJSON function:

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

To fill the table using $.getJSON as follows:

$.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>");
   }

})

다른 팁

I think that JS should not generate HTML (if it is possible). The good practice is to create separated action, that will be returns HTML. In this action you will call your API method, and in View you generate your table. IN JS you should only make an Ajax request to new action (and pass dataType: 'html' to ajax settings object).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top