最有效的* *的方式来填充选择与jQuery阿贾克斯 [英] most *efficient* way to populate select with Jquery ajax

查看:90
本文介绍了最有效的* *的方式来填充选择与jQuery阿贾克斯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我填充使用JQuery Ajax的几个选择。大多数负载罚款。有其中的一个查询或两个然而,在极少数情况下,返回记录了很多的选择。我在想,如果我正在填充选择的方式是最有效的方式从客户端code这么做。

我省略了一些东西,使codeA痘痘更短。

  $(函数(){
    FillAwcDll()
});
传播FillAwcDll(){
FillSelect('poleDdl','WebService.asmx /极',参数,可以假,空,假);
}

函数ServiceCall(方法,参数,onSucess,onFailure){
    变种PARMS ={+(($ .isArray(参数))parameters.join(,):参数)+}; //为JSON
    VAR定时器= setTimeout的(tooLong,100000);
    $阿贾克斯({
        键入:POST,
        网址:为approot +/服务/+方法,
        数据:PARMS,
        的contentType:应用/ JSON的;字符集= UTF-8,
        数据类型:JSON,
        成功:函数(MSG){
            clearTimeout(定时器);
            警报(成功);
            如果(typeof运算onSucess =='功能'|| typeof运算onSucess =='对象')
                onSucess(msg.d);
        },
        错误:函数(MSG,ERR){

            }
        }
    });

功能FillSelect(SEL,服务,参数,hasVa​​lue的,及时的,propCase){
    。VAR SELECTID ='选择#{0}格式(SEL);
    如果($(SELECTID)== NULL){
        警报(无效FillSelect ID');
        返回;
    }
    $(SELECTID +'选项')删除()。
    $('<选项类= \'装\价值= \'\'>加载...< /选项>')。appendTo(SELECTID);
    ServiceCall(服务,
                参数,
                功能(数据,参数){
                    $(SELECTID +'选项')删除()。

                    如果(提示=空&安培;!&安培; prompt.length大于0){
                        $('<选项类= \'selectPrompt \价值= \'\'选择> {0}< /选项>'格式(提示))appendTo(SELECTID)。
                    }
                    $每个(数据,(hasVa​​lue的)
                        ?功能(I,V){
                            $('<期权价值= \'{0} \> {1}< /选项>格式(v.Key,(propCase)v.Value.toProperCase():?v.Value)) .appendTo(SELECTID);
                        }
                        :功能(I,V){
                            $('<期权价值= \'{0} \> {1}< /选项>格式(V,(propCase)v.toProperCase():V)?)appendTo(SELECTID)。
                        })

                },
                FailedServiceCall);
                }

String.prototype.format =功能(){
    VAR模式= / \ {\ D + \} /克;
    变参=参数;
    返回this.replace(模式,功能(捕获){返回的args [capture.match(/ \ D + /)];});
}
 

因此​​,这只是循环周围,充满了选择。有没有更好的办法做到这一点?注意警报(成功)火线几乎立即,这样数据就回来快,但在那之后它挂试图填补的选择。

更新:(3)这工作真的很好。虽然有一些问题。我的onblur(调用函数重载选择),当的onblur被激活,选择重新装入,页面只需要永远载入,只要我拥有阻止它......不知道为什么?

  ServiceCall(服务,
            参数,
            功能(数据,参数){
                变量$选择= $(SELECTID);
                VAR vSelect ='';
                如果(提示=空&安培;!&安培; prompt.length大于0){
                    vSelect + ='<选项类= \'selectPrompt \价值= \'\'选择> {0}< /选项>'格式(提示);
                }
                如果(hasVa​​lue的){
                    $每个(数据,功能(I,V){
                        vSelect + ='<期权价值= \'{0} \> {1}< /选项>格式(v.Key,(propCase)v.Value.toProperCase():v.Value)。 ;
                    });
                }
                其他 {
                    $每个(数据,功能(I,V){
                        。vSelect + ='<期权价值= \'{0} \> {1}< /选项>格式(V,(propCase)v.toProperCase():V);
                    });
                }
                $ select.html(vSelect);
                删除vSelect;
                删除数据;
            },
            FailedServiceCall);
}
 

解决方案

您是否尝试过在内存中创建一个jQuery对象并填充的,并在年底把它在DOM?

像这样

  VAR vSelect = $('<选择/>'); //我们的虚拟选择元素
 

每个的方法使用该追加选项

  vSelect.append('<选项> ..< /选项>');
 

,并在年底追加的DOM虚拟对象的HTML

  $(SELECTID)。html的(vSelect.html());
 


别的东西,会加速你的当前code是保持一个引用选择元素(而不是它的id的 的)和追加到它,而不是直接具有的jQuery查找每个追加元素(,你现在要做的的)


更新以饱满的code

替换里面FilLSelect部分

  ServiceCall(服务,
            参数,
            < SNIP> ...< SNIP>中
            FailedServiceCall);
            }
 

  ServiceCall(服务,
            参数,
            功能(数据,参数){
                变量$选择= $(SELECTID);
                VAR vSelect ='';
                如果(提示=空&安培;!&安培; prompt.length大于0){
                     vSelect + ='<选项类= \'selectPrompt \价值= \'\'选择> {0}< /选项>'格式(提示);
                }
                如果(hasVa​​lue的)
                {
                   $每个(数据,功能(I,V){
                        vSelect + ='<期权价值= \'{0} \> {1}< /选项>格式(v.Key,(propCase)v.Value.toProperCase():v.Value)。 ;
                    });
                }
                其他
                {
                   $每个(数据,功能(I,V){
                        。vSelect + ='<期权价值= \'{0} \> {1}< /选项>格式(V,(propCase)v.toProperCase():V);
                    });
                }
                 $ select.html(vSelect);

            },
            FailedServiceCall);
            }
 

如果您页可以带回整个数据作为字符串中的格式

<$c$c>option_value:option_text<TAB>option_value:option_text<TAB>option_value:option_text...那么你可以做一个替换常规EX pression,只是把它在选择元素。

  VAR选项= data.replace(/([\ S] +)(=:)(:?)([\ S] +)/ GI,'&LT;期权价值=$ 1&GT; $第3版; /选项&GT;');
$(SELECTID).empty()追加(选项)。
 

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

解决方案

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

这篇关于最有效的* *的方式来填充选择与jQuery阿贾克斯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆