2016-12-30 28 views
0

我正在使用ajax檢查我的數據庫中的電子郵件ID。我正在使用keyUp事件來實時檢查它。它的工作正常,但我的鍵盤卡住了。請建議Keyup事件掛起我的筆記本電腦(我的鍵盤卡住了)

$(「#email」)。on(「keyup」,function(){ });

$("#email").on("keyup",function(){ 
 
      // now check if email id is changed 
 
      var e= $("#email").val(); 
 
      if(e!="<?=$user_info[0]['user_email']?>" && e!=""){ 
 
        $.ajax({ 
 
        url:"<?=URL?>users/check-user-email", 
 
        type:'get', 
 
        async:false, 
 
        data:{email:e}, 
 
        success:function(resp){ 
 
         console.log(resp); 
 
         if(resp=="Email exists"){ 
 
         $("#emailerror").css({'display':'block'}); 
 
         $("#submit").prop("disabled",true); 
 
         
 
         }else{ 
 
         $("#emailerror").css({'display':'none'}); 
 
          $("#submit").prop("disabled",false); 
 
         
 
         } 
 
        } 
 
       }); 
 
      } 
 
});

回答

1

你不應該使用async:false,它對同步調用,這不需要Ajax實現一個異步調用。

在你的情況,因爲你沒有任何反彈方法,用於在特定時間過後發射某些事件。超時可用於創建去抖動。如:

var time; 
$("#email").on("keyup", function() { 
    if (time) { 
    clearTimeout(time); // <----clears the timeout for every stroke but **last**. 
    }// so if you keyup for "abc" then call for 3rd stroke initialized for the word "abc". 
    time = setTimeout(function() { 
    // now check if email id is changed 
    var e = $("#email").val(); 
    if (e != "<?=$user_info[0]['user_email']?>" && e != "") { 
     $.ajax({ 
     url: "<?=URL?>users/check-user-email", 
     type: 'get', 
     //async: false, // <-------remove it or comment out. 
     data: { 
      email: e 
     }, 
     success: function(resp) { 
      console.log(resp); 
      if (resp == "Email exists") { 
      $("#emailerror").css({ 
       'display': 'block' 
      }); 
      $("#submit").prop("disabled", true); 

      } else { 
      $("#emailerror").css({ 
       'display': 'none' 
      }); 
      $("#submit").prop("disabled", false); 

      } 
     } 
     }); 
    } 
    }, 500); // <----you can register for more than 500 ms. 
}); 
0

對於每個keyup,都會調用回調方法,這是它的主要原因。 取而代之的是你可以使用防抖這將使用下劃線JS一定interval.Check後召喚出此鏈接: http://underscorejs.org/#debounce

var someFunction = function(){ 
     // now check if email id is changed 
     var e= $("#email").val(); 
     if(e!="<?=$user_info[0]['user_email']?>" && e!=""){ 
       $.ajax({ 
       url:"<?=URL?>users/check-user-email", 
       type:'get', 
       async:false, 
       data:{email:e}, 
       success:function(resp){ 
        console.log(resp); 
        if(resp=="Email exists"){ 
        $("#emailerror").css({'display':'block'}); 
        $("#submit").prop("disabled",true); 

        }else{ 
        $("#emailerror").css({'display':'none'}); 
         $("#submit").prop("disabled",false); 

        } 
       } 
      }); 
     } 
} 

$("#email").on("keyup", _.debounce(someFunction, 1000, true)); 
相關問題