XMLHttpRequest readystate不显示4

时间:2014-09-20 05:43:25

标签: ajax xmlhttprequest

为什么我总是得到XMLHttpRequest readystate而不是4 我也将它打印在始终显示1,2,3的警报框中 即时完成,请检查并告诉我任何建议或建议,热烈欢迎

var xmlHttp;
xmlHttp = CreateXMLHttpRequestObject();

function CreateXMLHttpRequestObject() {
    var isValidObj = true;

    if (window.ActiveXObject) {
        try {
            xmlHttp = new ActiveXObject();
        }
        catch (ex) {

            isValidObj = false;
        }
    }
    else {
        if (window.XMLHttpRequest) {
            try {
                xmlHttp = new XMLHttpRequest();
            }
            catch (ex) {

                isValidObj = false;
            }


        }
    }
    if (!isValidObj) {
        alert("Your browser do not support ajax");

    }
    return xmlHttp;

}

function Process() {
    if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {

        var food = encodeURIComponent(document.getElementById('txtFood').value);
        xmlHttp.open("GET", "Default.aspx?food=" + food, true)
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.send();
    }

}
function handleServerResponse() {
    if (xmlHttp.readyState == 4) {
        if (xmlHttp.status == 200) {
            var strResponse = xmlHttp.responseText;
            document.getElementById("divResult").innerHTML = "<span style='color:blue'>" + strResponse + " </span>";
            setTimeout('process()', 1000)
        }
    }
    else {
        alert(xmlHttp.readyState);

    }
}

1 个答案:

答案 0 :(得分:0)

你的代码应该像我这样不需要你的process()函数 xmlhttp.onreadystatechange事件会自动调用每个状态更改。

var food = encodeURIComponent(document.getElementById('txtFood').value);

xmlhttp.onreadystatechange=function()
{
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
  {
       var strResponse = xmlHttp.responseText;
        document.getElementById("divResult").innerHTML = "<span style='color:blue'>" + strResponse + " </span>";
  }
  else
  {
    alert(xmlHttp.readyState);
  }
}

xmlHttp.open("GET", "Default.aspx?food=" + food, true);
xmlHttp.send();