使用 Jquery ajax 填充 select 的最*有效*方法
我有几个使用 JQuery Ajax 填充的选择。大多数负载良好。然而,其中一两个查询在极少数情况下会返回大量记录到选择。我想知道我填充选择的方式是否是从客户端代码执行此操作的最有效方法。
我省略了一些东西以使代码更短一些。
$(function () {
FillAwcDll()
});
function FillAwcDll() {
FillSelect('poleDdl', 'WebService.asmx/Pole', params, false, null, false);
}
function ServiceCall(method, parameters, onSucess, onFailure) {
var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json
var timer = setTimeout(tooLong, 100000);
$.ajax({
type: "POST",
url: appRoot + "/services/" + method,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
clearTimeout(timer);
alert("success");
if (typeof onSucess == 'function' || typeof onSucess == 'object')
onSucess(msg.d);
},
error: function (msg, err) {
}
}
});
function FillSelect(sel, service, param, hasValue, prompt, propCase) {
var selectId = 'select#{0}'.format(sel);
if ($(selectId) == null) {
alert('Invalid FillSelect ID');
return;
}
$(selectId + ' option').remove();
$('<option class=\'loading\' value=\'\'>loading...</option>').appendTo(selectId);
ServiceCall(service,
param,
function (data, args) {
$(selectId + ' option').remove();
if (prompt != null && prompt.length > 0) {
$('<option class=\'selectPrompt\' value=\'\' selected>{0}</option>'.format(prompt)).appendTo(selectId);
}
$.each(data, (hasValue)
? function (i, v) {
$('<option value=\'{0}\'>{1}</option>'.format(v.Key, (propCase) ? v.Value.toProperCase() : v.Value)).appendTo(selectId);
}
: function (i, v) {
$('<option value=\'{0}\'>{1}</option>'.format(v, (propCase) ? v.toProperCase() : v)).appendTo(selectId);
})
},
FailedServiceCall);
}
String.prototype.format = function () {
var pattern = /\{\d+\}/g;
var args = arguments;
return this.replace(pattern, function (capture) { return args[capture.match(/\d+/)]; });
}
所以这只是循环并填充选择。有更好的方法吗?请注意,警报(“成功”)行几乎立即触发,因此数据很快就会返回,但之后它会挂起并尝试填充选择。
更新:(3)这工作得很好。虽然有一些问题。我有 onBlur(调用函数来重新加载选择),当 onBlur 被激活并且选择重新加载时,页面只需要永远加载,这么长时间我必须停止它......不知道为什么?
ServiceCall(service,
param,
function (data, args) {
var $select = $(selectId);
var vSelect = '';
if (prompt != null && prompt.length > 0) {
vSelect += '<option class=\'selectPrompt\' value=\'\' selected>{0}</option>'.format(prompt);
}
if (hasValue) {
$.each(data, function (i, v) {
vSelect += '<option value=\'{0}\'>{1}</option>'.format(v.Key, (propCase) ? v.Value.toProperCase() : v.Value);
});
}
else {
$.each(data, function (i, v) {
vSelect += '<option value=\'{0}\'>{1}</option>'.format(v, (propCase) ? v.toProperCase() : v);
});
}
$select.html(vSelect);
delete vSelect;
delete data;
},
FailedServiceCall);
}
I have several selects that I populate using JQuery Ajax. Most load fine. There are one or two of these queries however, that in a few rare cases return a LOT of records to the select. I was wondering if the way that I am populating the selects is the most efficient way to do so from client side code.
I omitted some stuff to make the code a litle shorter.
$(function () {
FillAwcDll()
});
function FillAwcDll() {
FillSelect('poleDdl', 'WebService.asmx/Pole', params, false, null, false);
}
function ServiceCall(method, parameters, onSucess, onFailure) {
var parms = "{" + (($.isArray(parameters)) ? parameters.join(',') : parameters) + "}"; // to json
var timer = setTimeout(tooLong, 100000);
$.ajax({
type: "POST",
url: appRoot + "/services/" + method,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
clearTimeout(timer);
alert("success");
if (typeof onSucess == 'function' || typeof onSucess == 'object')
onSucess(msg.d);
},
error: function (msg, err) {
}
}
});
function FillSelect(sel, service, param, hasValue, prompt, propCase) {
var selectId = 'select#{0}'.format(sel);
if ($(selectId) == null) {
alert('Invalid FillSelect ID');
return;
}
$(selectId + ' option').remove();
$('<option class=\'loading\' value=\'\'>loading...</option>').appendTo(selectId);
ServiceCall(service,
param,
function (data, args) {
$(selectId + ' option').remove();
if (prompt != null && prompt.length > 0) {
$('<option class=\'selectPrompt\' value=\'\' selected>{0}</option>'.format(prompt)).appendTo(selectId);
}
$.each(data, (hasValue)
? function (i, v) {
$('<option value=\'{0}\'>{1}</option>'.format(v.Key, (propCase) ? v.Value.toProperCase() : v.Value)).appendTo(selectId);
}
: function (i, v) {
$('<option value=\'{0}\'>{1}</option>'.format(v, (propCase) ? v.toProperCase() : v)).appendTo(selectId);
})
},
FailedServiceCall);
}
String.prototype.format = function () {
var pattern = /\{\d+\}/g;
var args = arguments;
return this.replace(pattern, function (capture) { return args[capture.match(/\d+/)]; });
}
So this just loops around and fills the selects. Is there a better way to do this? Note the alert("success") line fire almost immediately, so the data is coming back fast, but then after that it hangs trying to fill the select.
UPDATE: (3) this is working really well. Although there is some issue. I have onBlur(call function to reload selects) and when the onBlur is activated and the selects re-load, the page just takes FOREVER to load, so long I has to stop it... not sure why?
ServiceCall(service,
param,
function (data, args) {
var $select = $(selectId);
var vSelect = '';
if (prompt != null && prompt.length > 0) {
vSelect += '<option class=\'selectPrompt\' value=\'\' selected>{0}</option>'.format(prompt);
}
if (hasValue) {
$.each(data, function (i, v) {
vSelect += '<option value=\'{0}\'>{1}</option>'.format(v.Key, (propCase) ? v.Value.toProperCase() : v.Value);
});
}
else {
$.each(data, function (i, v) {
vSelect += '<option value=\'{0}\'>{1}</option>'.format(v, (propCase) ? v.toProperCase() : v);
});
}
$select.html(vSelect);
delete vSelect;
delete data;
},
FailedServiceCall);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您是否尝试过在内存中创建一个 jquery 对象并填充该对象,最后将其放入 DOM 中?
像这样
,在
each
方法中使用它来附加options
,最后在 DOM 中附加虚拟对象的 html ,
其他可以加快当前代码速度的东西是保留对
select
元素(而不是其 id)的引用并直接附加到它,而不是让 jquery 在每个附加中查找元素(像现在一样< /em>)使用完整代码更新
请将 FilLSelect 中的部分替换
为
如果页面可以将整个数据以字符串形式返回,格式为
option_value:option_textoption_value:option_text<, TAB>option_value:option_text...
然后您可以使用正则表达式进行替换,然后将其放入 select 元素中。Have you tried creating a jquery object in memory and populating that, and at the end putting it in the DOM?
like this
and in the
each
method use that to append theoptions
and at the end append in the DOM the virtual object's html
something else that would speed your current code is to keep a reference to the
select
element (instead of its id) and append to it directly instead of having jquery find the element in each appending (as you do now)Update with full code
replace the part inside FilLSelect
with
if you page can bring back the whole data as a string in the format of
option_value:option_text<TAB>option_value:option_text<TAB>option_value:option_text...
then you could do a replace with a regular expression and just put it in the select element.这是一个通用的,其中 msg 是从服务器返回的 JSON 数据对象。
就我个人而言,我更喜欢使用模板系统从 javascript 插入 html。我使用 Microsoft 的 jQuery 模板。其语法很简单:
选择权在你手中。 :)
Here is a generic one where msg is your JSON data object returned from the server.
Personally, I prefer using a templating system to insert html from javascript. I use Microsoft's jQuery Templates. The syntax for that would be simple:
The choice is yours. :)
创建一个不附加到 dom 的临时容器。
用选项填充容器后,将所有子项附加到选择。
也许这也会起作用:
Create a temporary container that is not attached to the dom.
After filling the container with the options attach all children to the select.
Maybe this will work too: