阿贾克斯上发送" KEYUP"重复的结果,当快速打字! [英] Ajax sent on "keyup" duplicates results when fast typing!

查看:124
本文介绍了阿贾克斯上发送" KEYUP"重复的结果,当快速打字!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的Ajax:

$("form[0] :text").live("keyup", function(event) {

    event.preventDefault();
    $('.result').remove();
    var serchval = $("form[0] :text").val();

    if(serchval){

        $.ajax({

            type: "POST",
            url: "<?= site_url('pages/ajax_search') ?>",
            data: {company : serchval},
            success: function(data) {

                var results = (JSON.parse(data));
                console.log(results);

                if(results[0]){
                    $.each(results, function(index) {
                        console.log(results[index].name);
                        $("#sresults").append("<div class='result'>" + results[index].name + "</div>");
                    });
                }
                else {
                    $("#sresults").append("<div class='result'>לא נמצאו חברות</div>");
                }
            }
        });
    }
});

当我输入很慢(慢然后每秒信)我得到的结果正确的,当我输入速度快,我得到2次相同的结果。

When I type slowly (slower then a letter per second) I get the results correct, when I type faster I get 2 times the same results

例如:
缓慢的打字: RES1 RES2 RES3
快速打字: RES1 RES2 RES3 RES1 RES2 RES3

example:
slow typing: res1 res2 res3
fast typing: res1 res2 res3 res1 res2 res3

此外,在提高code任何意见会受到欢迎!

Also, any advice on improving the code would be welcome!

推荐答案

这就是正在发生的事情(伪code):

Thats what is happening (pseudocode):

当你输入速度慢:

.keyup1
.remove1
//asynchronous ajax1 request takes some time here...
.append1
.keyup2
.remove2
//asynchronous ajax2 request takes some time here...
.append2

当你输入速度快:

.keyup1
.remove1
//asynchronous ajax1 request takes some time here...
//and keyup2 happens before ajax1 is complete
.keyup2
.remove2
.append1
//asynchronous ajax2 request takes some time here...
.append2
//two results were appended _in a row_ - therefore duplicates

为了解决重复问题,你想使你的结果删除/追加一个原子操作 - 使用 .replaceWith

To solve duplicates problem, you would want to make your results removing/appending an atomic operation - using .replaceWith.

首先生成结果HTML块为字符串,然后执行 .replaceWith 而不是卸下摆臂 / .append

Build results HTML block first as string and then do the .replaceWith instead of .remove/.append:

var result = '';
for (i in results) {
    result += "<div class='result'>" + results[i].name + "</div>";
}

$("#sresults").replaceWith('<div id="sresults">' + result + '</div>');

还有一个问题(不涉及重复)可能是较旧的结果会覆盖早些时候抵达新(因为AJAX是异步的,服务器可以发出响应不接收请求相同的顺序)。

Another problem (not related to duplicates) may be that older result overwrites newer which arrived earlier (because AJAX is asynchronous and server may issue responses not in the same order it receives requests).

的一个方法来避免,这是附加往返标记(一种序列号),以每个请求,并响应检查它

One approach to avoid this is attaching roundtrip marker (kind of "serial number") to each request, and checking it in response:

//this is global counter, you should initialize it on page load, global scope
//it contains latest request "serial number"
var latestRequestNumber = 0;

$.ajax({
    type: "POST",
    url: "<?= site_url('pages/ajax_search') ?>",
    //now we're incrementing latestRequestNumber and sending it along with request
    data: {company : serchval, requestNumber: ++latestRequestNumber},
    success: function(data) {
        var results = (JSON.parse(data));
        //server should've put "serial number" from our request to the response (see PHP example below)
        //if response is not latest (i.e. other requests were issued already) - drop it
        if (results.requestNumber < latestRequestNumber) return;
        // ... otherwise, display results from this response ...
    }
});

在服务器端:

function ajax_search() {
    $response = array();

    //... fill your response with searh results here ...

    //and copy request "serial number" into it
    $response['requestNumber'] = $_REQUEST['requestNumber'];

    echo json_encode($response);
}

另一种方法是使阿贾克斯()要求同步,异步选项设置为。然而,这可能会暂时锁定浏览器,同时要求被激活(见文档

Another approach would be to make .ajax() requests synchronous, setting async option to false. However this may temporarily lock the browser while request is active (see docs)

,你也一定要引入超时为 algiecas 建议,以减少负载在服务器上(这是第三个问题,不涉及重复,也没有请求/响应顺序)。

And also you should definitely introduce timeout as algiecas suggests to reduce load on server (this is third issue, not related to duplicates nor to request/response order).

这篇关于阿贾克斯上发送&QUOT; KEYUP&QUOT;重复的结果,当快速打字!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆