开发者

Retrieving source code using XMLhttpRequest in javascript

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 g开发者_开发知识库et 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>


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

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.


You set up the XHR object in a variable called "req", but then your callback uses "xmlhttp".


You can't do a xmlHttpRequest to a different domain than your page, but you can still retrieve the contents with a proxy script in your domain:

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

And your javascript should look like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜