2014-08-28 49 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」)。