views:

27

answers:

1

I'm trying to make an AJAX GET request, but I simply cannot get it to work. I want to retrieve the HTML source of example.com. I've previously used JQuery to send AJAX requests, but I use JQuery only for its AJAX capabilities so it's a waste to include the 30KB file for one task. What is it that I'm doing wrong?

<script type="text/javascript">

var XMLHttpArray = [
    function() {return new XMLHttpRequest()},
    function() {return new ActiveXObject("Msxml2.XMLHTTP")},
    function() {return new ActiveXObject("Msxml2.XMLHTTP")},
    function() {return new ActiveXObject("Microsoft.XMLHTTP")}
];
function createXMLHTTPObject(){
    var xmlhttp = false;
    for(var i=0; i<XMLHttpArray.length; i++){
            try{
                    xmlhttp = XMLHttpArray[i]();
            }catch(e){
                    continue;
            }
            break;
    }
    return xmlhttp;
}
function AjaxRequest(url,method){
    var req = createXMLHTTPObject();
    req.onreadystatechange= function(){
            if(req.readyState != 4) return;
            if(req.status != 200) return;
            return req.responseText;
  }
    req.open(method,url,true);
    req.send(null);
}

function MakeRequst(){
var result=AjaxRequest("http://example.com","get");
alert(result);
}
</script>
+1  A: 

Returning a value from your state change handler won't do you any good - that code is waiting for something to happen, and it's invoked from the browser innards as the HTTP request is processed. It's asynchronous.

Instead of expecting a result like that, your state change handler must itself handle the response, as appropriate to your application.

function AjaxRequest(url,method){
  var req = createXMLHTTPObject();
  req.onreadystatechange= function(){
        if(req.readyState != 4) return;
        if(req.status != 200) return;
        alert(req.responseText);
  }
  req.open(method,url,true);
  req.send(null);
}
Pointy
I don't know what's up. Thanks for the advice, but it still doesn't seem to work. Here's what I have: http://docgen.co.cc/test.html
Austin W80
You know that the URL in the AJAX request has to be made to the same domain as the page that has the code, right? For example that page is at "docgen.co.cc", so the URL of the AJAX request **must** be also be a page at "docgen.co.cc". That's called the "Same Origin Policy."
Pointy
Nope, did not know that. No wonder why.. Guess I'll stick to JQuery.
Austin W80
Well jQuery won't help - it's a rule imposed by the browser. You can use a different technique ("JSONP") to access services on other domains, if they're available in that form.
Pointy
Oh, I don't know what I'm thinking today. I guess I just confused PHP's file_get_contents() with AJAX somehow. Thanks for all your help.
Austin W80