最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ajax responseText comes back as undefined - Stack Overflow

programmeradmin1浏览0评论

I'm having problems with this piece of code; the return value es back as 'undefined'. What's the problem?

var fx = null;
xmlhttp.open("GET", URL ,false);
xmlhttp.onreadystatechange=function() 
    {
        alert("enter func");            
    if (xmlhttp.readyState==4) 
        {
        if (xmlhttp.status == 200) 
            {                   
                alert(fx);                  
                fx = xmlhttp.responseText;
                return fx;
            }
        else
            {
                alert("Error" + xmlhttp.statusText);
            }
        }
    }

Newer code:

function getData(callback)
 {      
    xmlhttp.open("GET", URL ,false);
    xmlhttp.onreadystatechange=function() 
        {               
        if (xmlhttp.readyState==4) 
            {
            if (xmlhttp.status == 200) 
                {                   
                    alert(xmlhttp.responseText);
                    cbfunc(xmlhttp.responseText);                   
                }
            else
                {
                    alert("Error" + xmlhttp.statusText);
                }
        }
    }   
        xmlhttp.send(null);
 }

How I'm calling it:

getData( function cbfoo(txt)
         {
            //document.form.autodate.value=txt;
            alert(txt);
            alert(document.form.autodate.value);
         });`

I'm having problems with this piece of code; the return value es back as 'undefined'. What's the problem?

var fx = null;
xmlhttp.open("GET", URL ,false);
xmlhttp.onreadystatechange=function() 
    {
        alert("enter func");            
    if (xmlhttp.readyState==4) 
        {
        if (xmlhttp.status == 200) 
            {                   
                alert(fx);                  
                fx = xmlhttp.responseText;
                return fx;
            }
        else
            {
                alert("Error" + xmlhttp.statusText);
            }
        }
    }

Newer code:

function getData(callback)
 {      
    xmlhttp.open("GET", URL ,false);
    xmlhttp.onreadystatechange=function() 
        {               
        if (xmlhttp.readyState==4) 
            {
            if (xmlhttp.status == 200) 
                {                   
                    alert(xmlhttp.responseText);
                    cbfunc(xmlhttp.responseText);                   
                }
            else
                {
                    alert("Error" + xmlhttp.statusText);
                }
        }
    }   
        xmlhttp.send(null);
 }

How I'm calling it:

getData( function cbfoo(txt)
         {
            //document.form.autodate.value=txt;
            alert(txt);
            alert(document.form.autodate.value);
         });`
Share Improve this question edited Jan 12, 2011 at 20:22 nnbz asked Jan 12, 2011 at 18:48 nnbznnbz 331 gold badge2 silver badges7 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

Update based on your edit

function getData(callback)
 {       
    // you should  move the creation of xmlhttp in here
    // so you can make multiple getData calls if needed 
    // if you keep xmlhttp outside the function the different calls to getData will interfere 
    // with each other

    xmlhttp.open("GET", URL ,false); // false should be true, to make it async
    ...
                {                   
                    alert(xmlhttp.responseText);
                    cbfunc(xmlhttp.responseText); // your function gets passed as the 
                                                  // parameter "callback" but you're 
                                                  // using "cbfunc" here instead of "callback"
 ...
 getData(function cbfoo(txt) // you can omit the function name here
 ...

Fixing those issues should make the code work.

Old answer

You're calling the XMLHttpRequest in Synchronous mode, that means that it will block the script until the request has finished, since you're assigning the onreadystatechange callback after the blocking call (that means after the request has already finished) your code never gets notified.

Since the synchronous mode blocks the script, it also blocks the Browser's UI, so it's not remended to use this mode.

You should (for 99% of the cases) use the Asynchronous mode and use a callback to handle the data, since xmlhttp.open does not return the return value of the onreadystatechange callback, it simply returns undefined immediately when run in async mode.

Now a mon pattern is to write a wrapper for the request and pass an anonymous function to this wrapper, which later will get called back when the request has finished.

function doRequest(url, callback) {
    var xmlhttp = ....; // create a new request here

    xmlhttp.open("GET", url, true); // for async
    xmlhttp.onreadystatechange=function() {     
        if (xmlhttp.readyState==4) {
            if (xmlhttp.status == 200) {

                // pass the response to the callback function
                callback(null, xmlhttp.responseText);

            } else {
                // pass the error to the callback function
                callback(xmlhttp.statusText);
            }
        }
    }
    xmlhttp.send(null);
}

You can now do a request and supply a function that will get called as soon as the request finishes, inside of that function you then do whatever you want to do with the response.

doRequest('http://mysite./foo', function(err, response) { // pass an anonymous function
    if (err) {
        alert('Error: ' + err);

    } else {
        alert('Response: ' + response);
    } 
});

This is the mon programming model in the browser, always go with a asynchronous solution, if you block the script you block the whole Browser.

发布评论

评论列表(0)

  1. 暂无评论