Populating html list using Ajax call


/ Published in: jQuery
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // Get the json from the controller
  2. function GetListItems() {
  3. $.ajax({
  4. type: "POST",
  5. url: "/JsonService/GetItems",
  6. contentType: "application/json; charset=utf-8",
  7. data: "{}",
  8. dataType: "json",
  9. success: function (result) {
  10. DisplayListItems(result);
  11. },
  12. "error": function (result) {
  13. var response = result.responseText;
  14. alert('Error loading: ' + response);
  15. }
  16. });
  17. }
  18.  
  19. // Create list items and append them inside <ul> element
  20. function DisplayListItems(list) {
  21. $.each(list, function(index, element) {
  22. var itemHTML = ["<li>",
  23. "<div>",
  24. "<div>",
  25. element.Title,
  26. "</div>",
  27. "<div>",
  28. element.Description,
  29. "</div>",
  30. "</div>",
  31. "</li>"].join('\n');
  32. $(".list > ul").append(itemHTML);
  33. }
  34. }
  35.  
  36. // Controller method that serves json data
  37. public JsonResult GetItems()
  38. {
  39. IQueryable<Item> itemList = new DAO().GetList();
  40.  
  41. return Json(from e in itemList
  42. select new
  43. {
  44. Title = e.Title,
  45. Description = e.Description
  46. });
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.