Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

jquery - Manipulating the "data" from $.ajax success: function(data) {

i have this and a simple question to it.

$.ajax({
    type: "POST",
    url: "/",
    data: $(".form").serialize(),
    dataType: "html",
    success: function (data) {
        $("#id").html(data);
    }
});

Inside "data" is some html I am inserting into the DOM. Thats no problem. But I want to manipulate the "data" before doing so. How can I do that? For example there are some li elements in "data". How would I for example delete the last li element out of the "data" string before inserting it into the DOM?

I tried something like

$(data li:last)remove();

...but that didnt work.

Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You don't need a hidden DIV. If you want to convert an html string to a DOM fragment, simply call jQuery on it. In your example:

success: function(data) {
    var jqObj = jQuery(data);
    jqObj.find("li:last").remove();
    $("#id").empty().append(jqObj);
}

Some IE considerations though:

  • If your data is large, jQuerifying it in-place is slow in IE (at least with jQuery 1.2.6). In that case you may want to create a container for it like var div = jQuery("<div/>"); div.html(data); then manipulate it there before doing $("#id").html(div.html()).
  • If your data has invalid HTML (unclosed tags, etc) you may get weird failures in IE. Just make sure the html is well-formed.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...