SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Evangelist
    Join Date
    Jun 2005
    Posts
    436
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    One-line page content return?

    Code JavaScript:
    function getResponse(page){
        http.open("GET", page, true);{
        http.onreadystatechange = function(){ 
            if (http.readyState == 4){
                return http.responseText;
            }
        }
        http.send(null);
    }

    This was my feeble attempt to get a pages content to return from a function. Unfortunately, its returning as "undefined" before the readyState gets changed to 4. Is there anything I can do to make this work?

    Thanks,
    e39m5

  2. #2
    Google Engineer polvero's Avatar
    Join Date
    Oct 2003
    Location
    Mountain View
    Posts
    567
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    the logic is not correct. the return statement is in an inner function, and has nothing to do what getResponse will return. Have your getResponse take in a callback function instead.

    Code:
    function getResponse(page, callback){
      http.open("GET", page, true);{
      http.onreadystatechange = function(){
        if (http.readyState == 4){
          callback(http.responseText);
        }
      }
      http.send(null);
    }
    
    // usage
    getResponse('foo.php', function(response) {
      alert(response);
    });
    Last edited by polvero; Dec 1, 2007 at 01:18. Reason: cleaned up spacing

  3. #3
    SitePoint Evangelist
    Join Date
    Jun 2005
    Posts
    436
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Err I can't get this to work. The ultimate goal is to be able to run:

    var = getResponse(page);

    And then var will output the page content. I tried to get the callback function to set var, but it did not work.

    Any ideas? Is this possible?

    Thanks,
    e39m5

  4. #4
    Google Engineer polvero's Avatar
    Join Date
    Oct 2003
    Location
    Mountain View
    Posts
    567
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    var = getResponse(page);
    This is not even valid JavaScript. But even then, if you assigned it to a variable.
    Code:
    var response = getResponse(page);
    There is latency in the time it needs to get the response. Therefore, that is why you need the callback function


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •