检查用户名可用性?

Kir*_*lla 0 javascript jquery

我想要一些javascript + ajax来检查用户名的可用性.我有一些麻烦......

让我们想象一下当我们在模糊事件上检查用户名可用性时的情况.

如果我们得到这样的情景怎么办?

  • a)用户输入的用户名"kir"
  • b)关注另一个要素
  • c)ajax请求已启动(请求"kir"用户名的可用性)
  • d)用户关注用户名并再输入一个字母"kirA"(来自c的回复)尚未收到
  • e)关注另一个要素
  • f)ajax请求已启动(请求"kirA"用户名的可用性)
  • g)我们从c)得到答案telling user that username is available, but it not (because we're telling about "kir", but not "kirA").

我该怎么做才能避免这种情况?使用某种随机生成的令牌来检查答案的有效性?

谢谢

Dav*_*und 5

您应该在创建新XHR时使用XHR.

var ongoingRequest = null;

function test() {
   if(ongoingRequest != null) {
      ongoingRequest.abort();
   }

   ongoingRequest = $.ajax( ... );
}
Run Code Online (Sandbox Code Playgroud)

当您收到响应时,您可以添加额外的功能以再次验证:

$.ajax({
   ...
   data: { query: query },
   success: (function(q) {
       return function(result) {
          if( $('#myTxt').val() != q) {
             // the textbox value is not the same as the query was
             // at the time of creating this response!
             return false;
          }

          ...
       }
   })(query)
});
Run Code Online (Sandbox Code Playgroud)


Anu*_*rag 5

您需要在XHR请求对象和它包含的用户名查询之间进行某种映射.或者在服务器对AJAX查询的响应中,也包括用户名.回复可能如下:

{
    username: "kir",
    available: false
}
Run Code Online (Sandbox Code Playgroud)

在回调中,验证当前文本框值是否与返回的用户名相同.如果是,则显示错误,否则忽略该响应.