2014-08-28 57 views
0

我有一个JS函数,它使用ajax过滤子导航/过滤器菜单中的选项。Ajax成功JSON循环

它正确地调用并接收来自服务器的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

您没有添加到'#searchResults',每次通过循环时都覆盖它的内容。尝试使用'.append()'来代替。 – sWW 2014-08-28 11:02:44

回答

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>"); 
     }); 
     } 
    }); 
    } 
+0

你先生,是个天才!您的答案与Shail的答案差不多,但您也包括之前结果的“许可”。完美工作。我会尽快将其标记为答案(9分钟!)。再次感谢! – 2014-08-28 11:06:47

+2

我更喜欢'$(“#searchResults”)。empty();''over'$(“#searchResults”)。html('');' – sWW 2014-08-28 11:07:14

+1

你是对的 - 它也更快。将编辑答案。 – 2014-08-28 11:08:19

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

你应该使用:

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

否则,你在每个循环覆盖你的 “#searchResults”)。