开发者

Most efficient way to create form with Jquery based on server data

开发者 https://www.devze.com 2023-02-02 03:09 出处:网络
I have a database webmethod that I call via Jquery ajax. This returns an array of data objects from the server. For each data object I want to populate a form with maybe a couple dozen fields.

I have a database webmethod that I call via Jquery ajax. This returns an array of data objects from the server. For each data object I want to populate a form with maybe a couple dozen fields.

What is the most efficient way to generate and populate these forms.

Right now, I create a string of the html in my javascript code for each record and then add it to the page. Then I add some events to the new elements.

This works OK in firefox, about 700 ms total for an array of 6 elements, and 4500 ms for an array of 30 elements. However, this is an internal app for my company, and the clients can only use IE8 on their machines. In IE8, this takes 2-10 SECONDS! for and array of length 6 and 47 seconds the one time it was actually able to complete for an array of length 30. Not sure what the @#$% IE8 is doing, but anyways... I need something more efficient it seems...

Thanks!

MORE INFO:

Edit: first thing I do is:

$("#approvalContainer").empty();

Web method signature:

[WebMethod]
    public List<User> ContractorApprovals()

So I call the method and then do this with the data:

for (var i = 0; i < data.length; i++) {
            displayUserResult("#approvalContainer", data[i], false);
        }
        formEvents("#approvalContainer");
        $("#approvalContainer").show("slow");

displayUserResult looks like this:

var div = "<div style=\"width:695px开发者_如何学Go\" class=..........."
fillForm(div,data)
$("#approvalContainer").append(div)

formEvents does things like add click events, create styles buttons and add watermarks.

fillForm does stuff like this:

$(userForm).find(".form-web-userName").text(userObject._web._userName);

where userForm is the div created in the displayUserResult function, and userObject is one of the objects in the array returned by the ajax call.

Please let me know if you need more information.


You are doing too much DOM manipulation. Every .append and .find and .text inside your loop makes it slower.

The most efficient way is to build an entire HTML string and append that once. I'm not going to bother with the displayUserResult function, and just modify your function that handles the data:

var div = "<div style=\"width:695px\" class=...........",
    html = "";
for (var i = 0; i < data.length; i++) {
     // Keep adding on to the same html string
     html += div + data[i]._web._userName + "</div>";
}
// After the loop, replace the entire HTML contents of the container in one go:
$("#approvalContainer").html(html);

However, while this is fast, note that this is only appropriate if _userName doesn't contain special characters, or is already HTML escaped.

0

精彩评论

暂无评论...
验证码 换一张
取 消