开发者

Ajax only return readyState == 4 value

Ok I've looked everywhere for this. I'm cutting out a couple of the variable declarations, as I can ensure that my XMLHttpRequest is working.

function submit_edit_form()
{
    // id and title are already declared
    var x = ajax_edit_form_save(id, 'title', title);
    alert(x);
}
function ajax_edit_form_save(id, property, new_value)
{

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        // screw IE5 & IE6
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
       if (xmlhttp.readyState == 4 && xmlhttp.responseText != '')
       {    
            return xmlhttp.responseText;
       }
    }

    // myURL is already defined. I'm not troubleshooting this part, I know it's working
    xmlhttp.open("GET", myURL, true);
    xmlhttp.send();
}开发者_运维技巧

So when I call submit_edit_form(), which calls ajax_edit_form_save(), I get an alert 'undefined'. I know that the problem is that ajax_edit_form_save() is returning undefined on readyState 1. I'm scratching my head because I only have the return when readyState == 4. How can I hold off on the return value so that x gets the actual responseText?


Your function is returning even before the ajax call completes, since it is async. The return statement in your "onreadystatechange" will not have any effect because the value is returned to the caller of the method "onreadystatechange" which is the XMLHttpRequest obejct and not your code.

You should pass a callback function to your ajax_edit_form_save which is called when readystate is 4

See below:

function ajax_edit_form_save(id, property, new_value, funCallback) // ==> callback function
{

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        // screw IE5 & IE6
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function()
    {
       if (xmlhttp.readyState == 4 && xmlhttp.responseText != '')
       {    
            callback( xmlhttp.responseText ); // =============> callback function called
       }
    }

    // myURL is already defined. I'm not troubleshooting this part, I know it's working
    xmlhttp.open("GET", myURL, true);
    xmlhttp.send();
}

The call back function could be:

function handleReponse(resp) {
  // do something with resp
}

ajax_edit_form_save("myID", "myProperty",  "new value", handleResponse);


Where did you get that (x) from which file? I think, you forgot to mention URL value.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜