【问题标题】:Clear previous cached options in jQuery chosen for new AJAX submit清除 jQuery 中为新的 AJAX 提交选择的先前缓存的选项
【发布时间】:2013-08-07 11:01:03
【问题描述】:

在按键事件中为所选字段中键入的值自动填充 jquery 中的值。在第一次请求中,这很好。但是对于furthur keypress 事件,这些值将附加到先前附加的选项中。下面是我的回调代码。

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

是否可以在 ajax 调用之前清除选择的选项值。

【问题讨论】:

    标签: jquery jquery-chosen


    【解决方案1】:

    您可以将 jquery 配置为在不缓存的情况下执行 ajax 请求。

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

    这样,jQuery 将在您的 url 上添加一个名为 _ 的参数,并带有一个随机数,它会发出不同的请求并将所有内容发送到服务器,从而避免浏览器缓存。您也可以在$.ajax 命令中配置缓存,例如:

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

    【讨论】:

    • Ajax 调用未缓存。所选中附加的值与先前附加的值相加。需要清除之前的附加值并添加从按键事件(ajax 调用)获得的新值
    【解决方案2】:

    问题是您使用.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");
    }
    

    希望这对你有用。

    【讨论】:

    • 它不仅清除了我在之前的 AJAX 调用中填充的选项,它还清除了所选选择框中的值...
    • 啊,我以为你只想完成 AJAX。我更新了我的帖子,以便保留选择中的原始选项。这对你有用吗?
    【解决方案3】:

    将以下函数添加到 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(); 
      };
    

    这是解决你的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-01
      相关资源
      最近更新 更多