XMLHttpRequest responseText获取完整的源代码

时间:2014-05-20 14:51:57

标签: javascript jquery html ajax

我想获取一个页面的完整源代码,例如www.google.com

我有一个PHP文件来复制页面的源代码:

<?php
    echo file_get_contents('http://www.google.com');
?>

我获取源代码的功能:

function sendRequest() {
 var xmlhttp;
 if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
     xmlhttp = new XMLHttpRequest();
    }
 else {// code for IE6, IE5
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
         var source_code = xmlhttp.responseText;
         alert(source_code);
         var element = $(source_code).filter("#specificelement").html();
     }
    }
xmlhttp.open("GET","test2.php",true);
xmlhttp.send(); 
}

1)为什么不显示完整的源代码?是否有限制或我做错了什么? 我想在源代码中获得一个特定的元素。

2)如果我能够获得特定元素,是否有办法在src路径中添加内容?实际图像位于原始页面的外部服务器上。因此,我需要在实际图像之前添加服务器。

现在:<img src="/images/blah.jpg" />

我想要的是什么:<img src="http://server.com/images/blah.jpg" />

更新

如果我这样做,完整的源代码将显示在文本区域中。

document.getElementById("textarea").innerHTML = source_code;

有没有办法从这里只获取特定元素的代码?

1 个答案:

答案 0 :(得分:0)

当您通过file_get_contents获取代码时,AJAX请求会解释该代码,因为它的功能是AJAX解释响应。

祝你好运。