调用ajax post / get方法时浏览器冻结

时间:2013-08-14 00:53:49

标签: javascript performance freeze

我有两个ajax函数,只要它们被调用就会冻结窗口。

有没有办法防止这种行为? (纯javascript)。

这是两个功能:

function fetch_json_data(a)
{
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest() }

xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        var json_response = JSON.parse(xmlhttp.responseText);

        for (var key in json_response) 
        {               
            if(json_response[key] != null && json_response[key].length > 0)
            {
                var e = document.getElementById(key+".div");
                e.innerHTML = "<pre>"+json_response[key]+"</pre>";      

                var e = document.getElementById(key);
                e.setAttribute("class", "active");
                e.parentNode.parentNode.previousElementSibling.setAttribute("class", "active");

                results_status[key] = true;

                if (key.match("sh"))
                {
                    quick_info.children[2].innerHTML += key + ", ";
                }

                quick_info.setAttribute("class", "show-data");

                close_alert();
            }
        }
    }
}

xmlhttp.open("POST","ajax.php", false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(a);    
}

功能编号2:

function fetch_data(a, b)
{   
if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}

xmlhttp.onreadystatechange = function() {

    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        if (last_fetched_element != null) { last_fetched_element.removeAttribute("class") }

        last_fetched_element = document.getElementById(b.id+".div");

        var t = last_fetched_element;
        var response = xmlhttp.responseText;
        if (xmlhttp.responseText.length == 0) response = "No Data";
        t.innerHTML = "<pre>" + response + "</pre>";
        t.setAttribute("class", "show-data");

        document.getElementById(b.id).setAttribute("class", "active");

        close_alert();

        results_status[b.id] = true;
    }
}

xmlhttp.open("POST","ajax.php", false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(a); // "fname=Henry&lname=Ford"
}

我不知道为什么会这样。响应很快就到了,但是, 我会很高兴避免冻结。

2 个答案:

答案 0 :(得分:1)

这是因为您正在使用同步调用,请尝试异步

set the third parameter of open to true

答案 1 :(得分:0)

XMLHttpRequest.open()功能。第三个参数设置Async或Normal。将Async设置为true时,浏览器不会冻结。正常情况下,浏览器将冻结并等待加载所有内容。所以改变你的台词。

xmlhttp.open("POST","ajax.php", false);

要:

xmlhttp.open("POST","ajax.php", true);