2013-08-07 83 views
0

自動填充在按鍵事件中爲所選字段中鍵入的值選擇的jquery中的值。在第一個請求中,它很好。但對於furthur keypress事件,這些值將被附加到前面的附加選項。下面是我的回調代碼。清除之前在新AJAX中選擇的jQuery中的緩存選項提交

success: function(data) { 
each(data, function(index) { 
$(".chzn-select").append(
$('<option></option>') 
.val(data[index]) 
.html(data[index])); 
}); 
$(".chzn-select").trigger("liszt:updated"); 
} 

是否可以在ajax調用之前清除所選的選項值。

回答

0

你可以配置jquery在沒有緩存的情況下執行ajax請求。

$(document).ready(function() { 
    $.ajaxSetup({ cache: false }); 
}); 

有了這個,jQuery將在您的網址添加一個名爲_參數與一個隨機數,它將使一個diferent請求URL的一切信息到服務器,避免瀏覽器緩存。你也可以在你的$.ajax命令配置緩存,樣品:

$.ajax({ 
    // configs... 
    cache: false, 
    // configs... 
}); 
+0

Ajax調用不被緩存。所選擇的值將與前面的附加值相加。需要清除之前附加的值並添加從按鍵事件中獲得的新值(ajax調用) – selva

0

的問題是,您使用.append永不手動清除數據。後續的ajax請求沒有以任何方式「連接」到選擇/選擇框。最簡單的方法是在使用$(".chzn-select").html("");之前清除所有選項。但是,重置和每個新項目可能會導致附加的DOM更新。下面的代碼收集所有選項事先將它們插入一氣呵成,而不是:

// safely store original options in an array. You only need to call 
// this once. It's probably best to run this before initiating chosen() 
// to avoid possible conflicts. 
var originalOptions = []; 
$(".chzn-select").children("option").each(function(ind, elm) { 
    originalOptions.push(elm); 
}); 
// init chosen after 
$(".chzn-select").chosen(); 


// (the other code here) 

success: function(data) { 
    var newOptions = []; 
    $.each(data, function(index) { 
    newOptions.push($('<option/>').val(data[index]).html(data[index]).get(0)); 
    }); 

    // this line will clear *all* entries in the select. Therefore 
    // we combine originalOptions and newOptions, so that the original 
    // options are kept. If you want the ajax options to be listed first, 
    // switch the variables. 
    $(".chzn-select").html(originalOptions.concat(newOptions)); 
    $(".chzn-select").trigger("liszt:updated"); 
} 

希望這對你的作品。

+0

它不僅清除了我在之前的AJAX調用中填充的選項,還清除了所選擇的選擇框中的值... – selva

+0

啊,我以爲你只想完成AJAX。我更新了我的帖子,以便保留選擇中的原始選項。那對你有用嗎? –

0

添加以下功能到Chosen.jquery.js

Chosen.prototype.activate_field = function() { 
    this.container.addClass("chzn-container-active"); 
    this.active_field = true; 
    this.search_field.val(this.search_field.val()); 
    this.clear_prev_list(); 
    return this.search_field.focus(); 
}; 


Chosen.prototype.clear_prev_list = function() { 
    return this.container.find("li.active-result").remove(); 
    }; 

這是解決問題的烏爾

相關問題