weixin_33743703 2015-04-27 08:36 采纳率: 0%
浏览 37

.ajaxComplete无法正常工作

Hi i currently having a problem with firing .ajaxComplete function, whereby it should be working on a demo site. I'm refer to this function from here http://www.bitrepository.com/a-simple-ajax-username-availability-checker.html

Here are my code :

    <SCRIPT type="text/javascript">
<!--
/*
Credits: Bit Repository
Source: http://www.bitrepository.com/web-programming/ajax/username-checker.html 
*/

pic1 = new Image(16, 16); 
pic1.src = "loader.gif";

$(document).ready(function(){

$("#userID").change(function() { 

var usr = $("#userID").val();

if(usr.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle">&nbsp;Checking availability...');

    $.ajax({  
    type: "POST",  
    url: "check.php",  
    data: "userID="+ usr,  
    success: function(msg){  
   $("#status").ajaxComplete(function(event, request, settings){ 

    if(msg == "OK")
    { 

        $("#userID").removeClass('object_error'); // if necessary
        $("#userID").addClass("object_ok");
        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
    }  
    else  
    {  
        $("#userID").removeClass('object_ok'); // if necessary
        $("#userID").addClass("object_error");
        $(this).html(msg);
    }  

   });

 } 

  }); 

}
else
    {
    $("#status").html('<font color="red">The username should have at least <strong>4</strong> characters.</font>');
    $("#userID").removeClass('object_ok'); // if necessary
    $("#userID").addClass("object_error");
    }

});

});

//-->
</SCRIPT>

I had try to alert the msg , the check.php able to return back the msg value, but it stop on the .ajaxComplete() there where it does not trigger the function after the .ajaxComplete(). Please guide me through this. Thanks

  • 写回答

1条回答 默认 最新

  • weixin_33691598 2015-04-27 08:41
    关注

    From the document

    As of jQuery 1.8, the .ajaxComplete() method should only be attached to document.

    So

    $(document).ajaxComplete(function(event, request, settings){
    });
    

    But in your code, there is no need to use ajaxComplete, the success callback will be called only when the ajax call is finished, so you can just check the value of msg directly in it.

            $.ajax({
                type: "POST",
                url: "check.php",
                data: "userID=" + usr,
                success: function (msg) {
                    if (msg == "OK") {
                        $("#userID").removeClass('object_error'); // if necessary
                        $("#userID").addClass("object_ok");
                        $(this).html('&nbsp;<img src="tick.gif" align="absmiddle">');
                    } else {
                        $("#userID").removeClass('object_ok'); // if necessary
                        $("#userID").addClass("object_error");
                        $(this).html(msg);
                    }
                }
            });
    
    评论

报告相同问题?