使用 Jquery ajax 填充 select 的最*有效*方法

发布于 2024-09-30 11:10:06 字数 3706 浏览 3 评论 0原文

我有几个使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

伪装你 2024-10-07 11:10:06

您是否尝试过在内存中创建一个 jquery 对象并填充该对象,最后将其放入 DOM 中?

像这样

var vSelect = $('<select/>'); // our virtual select element

,在 each 方法中使用它来附加 options

vSelect.append('<option>..</option>');

,最后在 DOM 中附加虚拟对象的 html ,

$(selectId).html( vSelect.html() );

其他可以加快当前代码速度的东西是保留对 select 元素(而不是其 id)的引用并直接附加到它,而不是让 jquery 在每个附加中查找元素(像现在一样< /em>)


使用完整代码更新

请将 FilLSelect 中的部分替换

ServiceCall(service,
            param,
            <SNIP>...<SNIP>,
            FailedServiceCall);
            }

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 );

            },
            FailedServiceCall);
            }

如果页面可以将整个数据以字符串形式返回,格式为

option_value:option_textoption_value:option_text<, TAB>option_value:option_text... 然后您可以使用正则表达式进行替换,然后将其放入 select 元素中。

var options = data.replace( /([\S ]+)(?=:)(:)([\S ]+)/gi, '<option value="$1">$3</option>');
$(selectID).empty().append(options);

Have you tried creating a jquery object in memory and populating that, and at the end putting it in the DOM?

like this

var vSelect = $('<select/>'); // our virtual select element

and in the each method use that to append the options

vSelect.append('<option>..</option>');

and at the end append in the DOM the virtual object's html

$(selectId).html( vSelect.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

ServiceCall(service,
            param,
            <SNIP>...<SNIP>,
            FailedServiceCall);
            }

with

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 );

            },
            FailedServiceCall);
            }

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.

var options = data.replace( /([\S ]+)(?=:)(:)([\S ]+)/gi, '<option value="$1">$3</option>');
$(selectID).empty().append(options);
下壹個目標 2024-10-07 11:10:06

这是一个通用的,其中 msg 是从服务器返回的 JSON 数据对象。

var options = "";

$(msg).each(function() {
   options += $('<option />').val(yourValue).text(yourDisplayValue);
});


$(selectID).empty().append(options);

就我个人而言,我更喜欢使用模板系统从 javascript 插入 html。我使用 Microsoft 的 jQuery 模板。其语法很简单:

var options = $.tmpl("<option value="${yourValue}">${yourDisplayValue}</option>", msg);

$(selectID).empty().append(options);

选择权在你手中。 :)

Here is a generic one where msg is your JSON data object returned from the server.

var options = "";

$(msg).each(function() {
   options += $('<option />').val(yourValue).text(yourDisplayValue);
});


$(selectID).empty().append(options);

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:

var options = $.tmpl("<option value="${yourValue}">${yourDisplayValue}</option>", msg);

$(selectID).empty().append(options);

The choice is yours. :)

情感失落者 2024-10-07 11:10:06

创建一个不附加到 dom 的临时容器。
用选项填充容器后,将所有子项附加到选择。

var temp = $('<select></select>');
$('<option></option>').attr('value', 1).text('First').appendTo(temp);
$(selectId).children().remove();
temp.children().detach().appendTo($(selectId));

也许这也会起作用:

$(selectId).html(temp.html());

Create a temporary container that is not attached to the dom.
After filling the container with the options attach all children to the select.

var temp = $('<select></select>');
$('<option></option>').attr('value', 1).text('First').appendTo(temp);
$(selectId).children().remove();
temp.children().detach().appendTo($(selectId));

Maybe this will work too:

$(selectId).html(temp.html());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文