我已经花了很多年,并且不明白为什么它不起作用.我正在使用ajax发送一个帖子到php curl,它带来一个url然后回到ajax.当我发送警报时,该页面的所有html都会显示在警报中.现在我想使用jquery来查找每个元素,即body,h1,title和输出内容,但是当我这样做时它不适用于正文或标题.这是为什么?
这是我的jquery
$.ajax({
type: "POST",
url: "senddom.php",
data: {"dataString" : dataString },
success: function(response) {
$('body').append("<p> contents of title:" + $(this).find('title').html() + "</p>");
$('body').append("<p> contents of all: " + $(this).find('body').html() + "</p>");
$(response).find('h1').each(function() {
$('body').append("<p> contents of H1: " + $(this).text() + "</p>");
});
Run Code Online (Sandbox Code Playgroud)
这是我的PHP
<?php
$site= $_POST['dataString']; // get data
function curl_get($site){
$useragent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$site);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$data=curl_exec($ch);
curl_close($ch);
return $data;
}
function getdom($site){
$html = curl_get($site);
$xml = new DOMDocument();
@$xml->loadHTML($html);
echo($html);
}
echo getdom($site);
?>
Run Code Online (Sandbox Code Playgroud)
在你的成功块内:$(this)- >$(response)
跟进:全文HTML与碎片
虽然这似乎可以解决当前的问题,但这取决于您的响应是否是完整的HTML.
在这种情况下,似乎response 是全文HTML.
jQuery parseHTML方法不处理全文HTML,遗憾的是response无法正确解析.更多信息请参阅:https://github.com/jquery/jquery/blob/master/src/core.js
在您要解析全文HTML的情况下,一种方法是使用DOMParser API.值得注意的"text/html"是,目前缺乏对解析的支持; 仅适用于Firefox.document.implementation除了IE <9之外,其他方面都有支持.
也就是说,在你想要使用的情况下的一个例子DOMParser-
parser = new DOMParser();
doc = parser.parseFromString(response, "text/html");
$response = $(doc)
$response.find('title').text()
Run Code Online (Sandbox Code Playgroud)
您想要使用的示例documentation.implementation-
var doc = document.implementation.createHTMLDocument("");
var doc_el = doc.documentElement;
doc_el.innerHTML = response;
$response = $(doc_el); //
$response.find('title').text()
Run Code Online (Sandbox Code Playgroud)
有关更多信息,我将遵循我在github上找到的一个很好的jQuery插件(它涉及x-browser支持):jquery.parsehtml.js.
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |