Ajax成功JSON循环

时间:2014-08-28 11:00:48

标签: jquery ajax json

我有一个JS函数,它使用ajax来过滤子导航/过滤器菜单中的选项。

它正确地进行调用并从服务器接收JSON响应,但它不会循环遍历结果。

它只显示JSON响应中的最后一个结果。

ajax脚本:

function updateVenues(opts){
    $.ajax({
      type: "POST",
      url: "/venue-search/ajax/",
      dataType : 'json',
      cache: false,
      data: {filterOpts: opts, get_param: 'id'},
      success: function(records){
        $.each(records, function(idx, record){
         $("#searchResults").html('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
       });
      }
    });
  }

来自服务器的典型响应

[
{"id":"1","title":"Wedding Venue 1","main_image":"wedding-venue-1.jpg"},
{"id":"2","title":"Wedding Venue 2","main_image":"wedding-venue-2.jpg"},
{"id":"3","title":"Wedding Venue 3","main_image":"wedding-venue-3.jpg"}
]

有人能说清楚它为什么不循环吗?

3 个答案:

答案 0 :(得分:1)

每次调用.html时,它都会用新值覆盖整个内容,这就是为什么你只显示最后一个内容。您需要使用append

function updateVenues(opts){
    $.ajax({
      type: "POST",
      url: "/venue-search/ajax/",
      dataType : 'json',
      cache: false,
      data: {filterOpts: opts, get_param: 'id'},
      success: function(records){
        //clear out any previous results first
        $("#searchResults").empty();
        $.each(records, function(idx, record){
         //now append each one
         $("#searchResults").append('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
       });
      }
    });
  }

答案 1 :(得分:0)

试试这个

function updateVenues(opts){
$.ajax({
  type: "POST",
  url: "/venue-search/ajax/",
  dataType : 'json',
  cache: false,
  data: {filterOpts: opts, get_param: 'id'},
  success: function(records){
    $.each(records, function(idx, record){
     $("#searchResults").append('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");
   });
  }
});
  }

答案 2 :(得分:0)

您应该使用:

$("#searchResults").append('<a href="/venue-preview/' + record.id + '" class="various fancybox.ajax">' + record.title + "</a>");

否则你会在每个循环中覆盖你的&#34;#searchResults&#34;)。