在javascript中使用XMLhttpRequest检索源代码

时间:2011-01-18 20:36:22

标签: javascript xmlhttprequest

我试图通过在javascript中使用XMLhttpRequest来获取网站的源代码,但我无法获得响应。如何使用XMLhttpRequest获取源代码?这就是我现在所拥有的:

<script language="Javascript" type="text/javascript">
var req = new XMLHttpRequest();
req.open(
    "GET",
    "http://www.google.com",
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (req.readyState == 4) 
    {
        var docx=req.responseXML;
        alert(docx);
    }
}
</script>

3 个答案:

答案 0 :(得分:0)

您在名为“req”的变量中设置XHR对象,但是您的回调使用“xmlhttp”。

答案 1 :(得分:0)

您不能对与您的网页不同的域执行xmlHttpRequest,但您仍可以使用域中的代理脚本检索内容:

#proxy-script (proxy.php)
<?php
echo file_get_contents ( $_GET['url'] );
?>

你的javascript应该是这样的:

<script language="Javascript" type="text/javascript">
var myUrl = "http://www.google.com";
var req = new XMLHttpRequest();
req.open(
    "GET",
    "/proxy.php?url="+encodeURIComponent(myUrl),
    true);
req.onreadystatechange = statusListener;
req.send(null);

function statusListener()
{
if (xmlhttp.readyState == 4) 
    {
        var docx=xmlhttp.responseXML;
        alert(docx);
    }
}
</script>

答案 2 :(得分:0)

使用它代替给定的if语句。

    if (req.readystate == 4) {
        if (req.status == 200) {
            var docx=req.responseXML;           
            alert(docx);
            //Can also try this just in case:
            //var doc = req.responseText;
            //alert(doc);
        }
    }

您没有检查以确保状态正常,这可能会导致脚本失败,返回错误(由于它是Javascript,您可能看不到调试关闭,因为响应尚未准备好)直到就绪状态为4并且状态代码为200.此外,如果responseXML不起作用,请尝试使用responseText,因为它可能没有正确格式化。

相关问题