Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - Why does my jQuery AJAX function always return false?

function check_username(){
    $.ajax({
        type: "POST",
        dataType: 'json',
        url: "/ajax/check/username.html",
        data: "via=ajax&username="+$('input[name=register_username]').val(),
        success: function(msg){
            if(msg.response==false){
                register_username.parent().css('background-color','#db2e24');
                register_username.parent().parent().find('td:last-child').text(msg.message);
                register_username.focus();
                return false;
            } else {
                register_username.parent().css('background-color','#fff');
                register_username.parent().parent().find('td:last-child').text("");
                return true;
            }
       }
    });
}

I'm sorry if my English isn't good -- English is not my native language. Back to the topic, why does the function above always return false? FYI : the JSON is OK

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

check_username calls an ajax function which starts a networking operation and then returns immediately. check_username returns long before the ajax call finishes and the success handler gets called. Thus, the success handler has NOTHING to do with the value that check_username returns.

Since there is no return value in the check_username function itself (only in the embedded success handler function), check_username returns undefined which is a falsey value, thus you think it's always returning false.

If you want to do something with the return value from the success handler, then you have to either operate in the success handler itself or you have to call another function from the success handler. This is how asynchronous operations work.

Returning true or false from the success handler function does nothing. The success handler is called by the internals of the ajax handling code and returning from the success handler just goes into the bowels of the ajax internals. The return value from the success handler is not used in any way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...