HTML request returned from AJAX

How can I request the HTML returned from AJAX?

I tried

$.post("gethtml.php", { url: $url.val() }, function(data) {
    var $html = $(data),
            $links = $("link, script, style", $html),
            $body = $("body", $html);

    $links.each(function() { $(this).addClass("tmp"); });
    console.log($html);
    console.log($body.html());
});

$htmllooks like [meta, title, script, style#gstyle, script, textarea#csi, div#mngb, iframe, center, script, script]and $body.html()null

UPDATE

Easy setup at http://jsfiddle.net/uvnrJ/1/

$(function() {
  var html = "<!doctype html><html><head><title>title here ... </title></head><body>This is the body</body></html>",
      $html = $(html);
  console.log($html); // jQuery(title, <TextNode textContent="This is the body">)
  console.log($html.find("body")); // jQuery()
  console.log($html.find("title")); // jQuery()
  console.log($html.filter("title")); // jQuery(title)
});

Show that jQuery is having trouble parsing an HTML string?

+3
source share
4 answers

Try it...

..........
var elements = $('<div></div>');
elements.html(data);
alert(elements.find('body').html());
...........
+3
source

I think you should look for your elements directly in a variable dataor use a method find()on $(data). Sort of:

$.post("gethtml.php", { url: $url.val() }, function(data) {
    var $html = $(data).find('html'), // First way
        $links = $("link, script, style", data), // Second way
        $body = $("body", data); // Could be better written as $(data).find('body')

    $links.each(function() { $(this).addClass("tmp"); });
    console.log($html);
    console.log($body.html());
});
0
source

HTML :

    var headStartIndex = htmlString.toLowerCase().indexOf("<head>") + "<head>".length;
    var headEndIndex = htmlString.toLowerCase().indexOf("</head>");
    var newHead = htmlString.substring(headStartIndex, headEndIndex);

    var bodyStartIndex = htmlString.toLowerCase().indexOf("<body>") + "<body>".length;
    var bodyEndIndex = htmlString.toLowerCase().indexOf("</body>");
    var newBody = htmlString.substring(bodyStartIndex, bodyEndIndex);

    console.log(newHead);
    console.log(newBody);
0

you can try this, it works

$.ajax({
    'url': url,
    'dataType': 'html',
    'success': function(e){
        var $div = $("<div id='_some_id'>" + e + "</div>");
        $div = $div.filter("_some_id");
        $div.find("span"); // you can search for anything here. it would work now
    }
});
0
source

All Articles