简体   繁体   中英

How can I parse HTML returned from AJAX call

I am making a GET call to the server and it returns a String of HTML. I want to parse this HTML and only get the HTML with the id 'container'.

Here is my code:

   $("#name").click(function() {
     $.ajax({
            type : 'GET',
            url : "/",
            dataType : 'text',
            success : function(data) {
                var object = $('<div/>').html(data).contents(); //Convert the String into an object.
                var container = object.find('container'); //This successfully gets the object with the id 'container'
                console.info(container.html()); //Here is where I want to output just the HTML of the container.




            },
            error : function(data) {
                console.error("Error getting homepage");
            }
        });
        return false;
});

I want to just output the HTML that has the id 'container'. Right now it is outputting nothing. I don't think I am doing this in the best way.

ALSO: I am going to be loading the HTML into another element on the page.

This is what I used in my own code:

var xhr = new XMLHttpRequest();
var url = "http://....";
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        html = $.parseHTML( xhr.responseText );
        var container = $("#container", html);
    }
}

I was able to accomplish what I wanted with the following:

$("#name").click(function() {
     $.ajax({
            type : 'GET',
            url : "/",
            dataType : 'text',
            success : function(data) {
                var parser = new DOMParser();
                doc = parser.parseFromString(data, "text/html");
                var remainder = doc.getElementById("main-content").innerHTML;
               $("#r-div").replaceWith("<div id=\"main-content\">" + remainder + "</div>");
            },
            error : function(data) {
                console.error("Error getting homepage");
            }
        });
        return false;

});

This gets a HTML response then extracts "main-content" div and replaces "r-div" in the current page with the HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM