2011-03-23 53 views
3

如何查询从AJAX返回的HTML?查询从AJAX返回的HTML

我试图

$.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()); 
}); 

$html看起来像[meta, title, script, style#gstyle, script, textarea#csi, div#mngb, iframe, center, script, script]$body.html()

UPDATE

简单的设置在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) 
}); 

显示jQuery解析HTML字符串似乎有问题?

+0

你想做什么? – 2011-03-23 05:46:47

+1

您是否试过'$ body = $(data).find('body');'? – 2011-03-23 05:48:54

+0

@experimentX我想获得另一个网页的HTML源代码。 – 2011-03-23 08:32:33

回答

0

我认为你应该直接在data变量中搜索你的元素,或者在$(data)上使用find()方法。喜欢的东西:

$.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

这似乎不工作,你可以尝试一个非常简单的设置http://jsfiddle.net/uvnrJ/1/,你可以看到,jQuery似乎只是检测标题标记+文本节点。我认为这是问题的原因。有什么建议么? – 2011-03-26 13:10:05

+0

@jiewmeng是的,它似乎不可能使用jQuery。看看这个答案[jQuery的ajax解析响应文本](http://stackoverflow.com/questions/1050333/jquery-ajax-parse-response-text),特别是这一个[什么是解析远程内容与jQuery?](http://stackoverflow.com/questions/1034881/what-is-the-best-practice-for-parsing-remote-content-with-jquery) – 2011-03-26 18:28:23

0

我遇到了同样的问题,而被迫诉诸直接解析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); 
3

尝试......

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

你可以试试这个,这个作品

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