Javascript get request阻止了ui

时间:2014-07-16 00:05:50

标签: javascript jquery html ajax callback

请考虑以下事项:

HTML:

...
<button id="get">Get</button>
<div id="result"></div>
...

JavaScript的:

$('#get').on('click', function()
{
    var result = httpGet(getUrl() + 'query.php');
    document.getElementById('result').innerHTML = result;
});

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.open('GET', theUrl, false);
    xmlHttp.send(null);

    return xmlHttp.responseText;
}

function getUrl()
{
    return window.location.href.substring(0, (window.location.href.lastIndexOf('/')) + 1);
}

PHP(query.php):

// Make database query and return the result.

所以...当我点击button 获取时,它会调用httpGet()并向query.php发出请求,进行数据库查询并返回结果,已归为div 结果

问题是,在从服务器获得结果之前,这是一个缓慢的过程,ui被阻止。我该如何解决?

2 个答案:

答案 0 :(得分:3)

open的最后一个参数应该是&#34; true&#34;为了使它成为异步。

 xmlHttp.open('GET', theUrl, true);

这意味着您的请求将是异步的,并且不会阻止ui

当然,如果你这样做,你就不会在下一行中得到正确的答案,所以你的功能将是这样的:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById('result').innerHTML = xmlhttp.responseText;
        }
    }
    xmlHttp.open('GET', theUrl, false);
    xmlHttp.send(null);
}

答案 1 :(得分:2)

您通过将false作为第三个参数传递给XmlHttpRequestopen方法来同步发出请求。通过使true请求将是异步的,并且不会阻塞。

但是,这意味着您不能等待并返回当前正在执行的结果。您将不得不实现回调模式。这意味着您在AJAX请求完成后定义要调用的函数,以便应用程序的主线程不必等待结果继续。

由于您正在使用jQuery,因此您可以利用其简化的AJAX methods

$('#get').on('click', function()
{
    $.get(getUrl() + 'query.php', function(result) {
        $('#result').html(result);
    });
});

function getUrl()
{
    return window.location.href.replace(/(.*\/)[^/]*$/, "$1");
}

另请参阅上面的ID selectorhtml方法的jQuery文档。

相关问题