使用jquery ajax 动态生成下拉框代码如下:
$.ajax({
type:"get",
dataType:"json",
contentType:"application/json;charset=utf-8",
url:"{{ url_for('ajax_categorys') }}",
success:function(result){
$.each(result,function(index,value){
$("#ca").append("<option value='"+value.name+"'>"+value.name+"</option>");
})
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
async:false //false表示同步
}
);
这样可以在页面生成的时候动态加载下拉框数据,但当下拉框数据有改变后,再次点击仍然是初始加载的数据。
使用click事件则可以加载新的数据,但是会在已有数据下添加,则会有重复的数据出现。
在ajax里加上$("#ca").empty(); 可以清空现有选项,但是没法选择我需要的选项,因为当我点击其中一项选项时,又触发了另一次click事件。。。
$("#ca").click(function(){
$("#ca").empty();
$.ajax({
type:"get",
dataType:"json",
contentType:"application/json;charset=utf-8",
url:"{{ url_for('ajax_categorys') }}",
success:function(result){
$.each(result,function(index,value){
$("#ca").append("<option value='"+value.name+"'>"+value.name+"</option>");
})
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
},
async:false //false表示同步
}
);
});
我如何才能使每次得到的下拉框选项都是最新的数据并且可以选中为需要的选项??
When- clicks
- Initiate an ajax request to obtain the latest data.
- Clear all options before appending options.
After - is appended, add the attribute
#ca
, check whether there isoptions_loaded=1
, and if there is, no ajax request will be initiated. If not:#ca
to theoptions_loaded=1
element.The premise is that after the default user opens this page, clicks
#ca
, and loads the data, the data will not be updated. If the needs are opposite, then another idea needs to be used.1. Use html() instead of append() so you don’t need to clear it every time you click
2. If the click event prevents the event from bubbling, the update event will not be triggered by clicking on the option
1. If you want new data every time, you need to clear the cache and add a timestamp after the url;
2. Before loading data each time, clear the previously added data. You can also use the html()
mentioned above. var strHtml="";
$.each(result,function(index,value){
if(selected condition){
})
$("#ca").html(strHtml);
When making an ajax request, first record the currently selected id to a global variable, such as (origin_id)
Then after requesting the data, if the value of each id and origin_id is the same, add
selected=true
Then use innerHtml to replace the dom tree
I don’t know what your list is used for. It requires such strong synchronization of data. Usually drop-down lists read data from the cache. Even business data is loaded once on the page and read from the background.
The general approach is to directly write the json file for fixed options, which will load quickly. If it is non-fixed, use Ajax.