在 javascript 中使用 XMLhttpRequest 检索源代码 [英] Retrieving source code using XMLhttpRequest in javascript

查看:31
本文介绍了在 javascript 中使用 XMLhttpRequest 检索源代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get the source code of a website by using XMLhttpRequest in javascript, but I cannot get the response. How do I get source code using XMLhttpRequest? Here is what I have right now:

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

推荐答案

用它代替给定的 if 语句.

Use this in place of the given if statement.

    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,因为它可能没有正确格式化.

You're not checking to make sure the status is ok, this could make the script fail by returning an error (which you might not see if you have debugging off, due to it being Javascript) since the response is not ready until both the ready state is 4 and the status code is 200. Also, if responseXML doesn't work try responseText, as it might not be properly formatted.

这篇关于在 javascript 中使用 XMLhttpRequest 检索源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆