【问题标题】:Ajax only return readyState == 4 valueAjax 只返回 readyState == 4 值
【发布时间】:2010-08-06 13:47:55
【问题描述】:

好的,我到处找这个。我删除了几个变量声明,因为我可以确保我的 XMLHttpRequest 正常工作。

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

因此,当我调用 submit_edit_form()(它调用 ajax_edit_form_save())时,我会收到“未定义”警报。我知道问题是 ajax_edit_form_save() 在 readyState 1 上返回 undefined。我正在摸不着头脑,因为我只有在 readyState == 4 时才返回。我怎样才能推迟返回值以便 x 得到实际响应文本?

【问题讨论】:

    标签: javascript ajax xmlhttprequest


    【解决方案1】:

    您的函数甚至在 ajax 调用完成之前就返回了,因为它是异步的。您的“onreadystatechange”中的 return 语句不会产生任何影响,因为该值将返回给方法“onreadystatechange”的调用者,该方法是 XMLHttpRequest 对象,而不是您的代码。

    您应该将一个回调函数传递给您的 ajax_edit_form_save,当 readystate 为 4 时调用该函数

    见下文:

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

    回调函数可以是:

    function handleReponse(resp) {
      // do something with resp
    }
    
    ajax_edit_form_save("myID", "myProperty",  "new value", handleResponse);
    

    【讨论】:

    • 哥们,我想我爱你。我完全没有考虑到这一点。我正要检查一下,我会给你检查。
    【解决方案2】:

    您从哪个文件中得到那个 (x)?我想,你忘了提到 URL 值。

    【讨论】:

    • 这不是问题所在。我知道请求运行正常。我只需要处理返回值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 2016-04-06
    相关资源
    最近更新 更多