为什么我的jQuery AJAX函数总是返回false? [英] Why does my jQuery AJAX function always return false?

查看:214
本文介绍了为什么我的jQuery AJAX函数总是返回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;
            }
       }
    });
}

对不起,我的英语不好-英语不是我的母语. 回到主题,为什么上面的函数总是返回false? 仅供参考:JSON可以

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

推荐答案

check_username调用ajax函数,该函数启动联网操作,然后立即返回. check_username在ajax调用完成和成功处理程序被调用之前很久就返回.因此,成功处理程序与check_username返回的值无关.

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.

由于check_username函数本身没有返回值(仅在嵌入式成功处理程序函数中),因此check_username返回undefined这是一个假值,因此您认为它总是返回false.

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.

从成功处理程序函数返回truefalse不会执行任何操作.成功处理程序由ajax处理代码的内部调用,并且从成功处理程序返回的内容仅会进入ajax内部组件的内部.成功处理程序的返回值不会以任何方式使用.

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.

这篇关于为什么我的jQuery AJAX函数总是返回false?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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