使用select2分批异步加载大量数据
2016-05-09 本文已影响5727人
nummycode
最近在项目啊开发中需要从下拉列表中获取游戏ID,而后台游戏数据有将近25万条,这种情况下是不可能实现一次性加载的,只能分批异步加载。找了很多插件,都没有合适的,也想过自己做一个插件,无奈时间有限,任务比较紧,只能借助第三方插件,缩短项目时间。最终找到了select2这个插件。
html代码:
<link href="select2/select2.css" rel="stylesheet">
<link href="select2/select2-bootstrap.css" rel="stylesheet">
...
<select data-placeholder="请选择游戏..." class="select2" >
</select>
...
<script src="select2/select2.full.js"></script>
js代码
$(".select2").select2({
theme: "bootstrap",
allowClear: true,
placeholder: "请选择一个游戏",
ajax:{
url:"/analysis/search",
dataType:"json",
delay:250,
data:function(params){
return {
name: params.term,
page: params.page || 1
};
},
cache:true,
processResults: function (res, params) {
var games = res["data"]["games"];
var options = [];
for(var i= 0, len=games.length;i<len;i++){
var option = {"id":games[i]["gid"], "text":games[i]["gname"]};
options.push(option);
}
return {
results: options,
pagination: {
more:res["data"]["more"]
}
};
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1
}
});
flask代码
后台使用flask编写的,代码如下:
@ANALYSIS.route("/search", methods=["GET"])
def search_games():
"""
获取游戏
:return:
"""
params = request.args
name = params.get("name", None)
page = params.get("page", 0)
page = int(page) - 1
skip = page * 50
data = dict()
if name:
games, count = get_games_by_name(name, skip)
data["games"] = games
data["count"] = count
else:
games, count = get_first_50_games(skip)
data["games"] = games
data["count"] = count
print data["count"]
more = page * 50 < data["count"]
data["more"] = more
return successify(data=data)