如何让这个函数返回true或false

guan_tu 2014-09-16 09:20:00

//使用ajax验证用户名是否存在
$("#cateMgr").submit(function () {
if ($.trim($("#cateName").val()) == "") {
$("#msg").html("用户名不能为空!").css("color", "red");
return false;
}
$.ajax({
url: "@Url.Action("CheckCateExists")",
type: "POST",
data: "categoryName=" + $("#cateName").val(),
dataType: "text",
success: function (result) {
if (result == "用户名已经存在") {
$("#msg").html(result).css("color", "red");
return false;
} else {
$("#msg").html(result).css("color", "green");
return true;
}
},
error: function () {
alert("发生错误");
}
});
});

当用户名为空时返回false,表单不提交,但是当用户名不为空时,无论用户名是否存在,表单都会提交,也就是说我写在回调函数中的 return true/false 并不是这个submit事件的返回值,如何才能使这个函数总是返回一个bool呢?
...全文
1139 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Go 旅城通票 2014-09-16
  • 打赏
  • 举报
回复
ajax要同步请求,异步返回值无效,回调里面返回值也无效
    $("#cateMgr").submit(function () {
        if ($.trim($("#cateName").val()) == "") {
            $("#msg").html("用户名不能为空!").css("color", "red");
            return false;
        }
        var rst = false; ///////////////////////
        $.ajax({
            url: "@Url.Action("CheckCateExists")",
            type: "POST",
            data: "categoryName=" + $("#cateName").val(),
            dataType: "text",
            async: false, ///////////////////////这个最关键
            success: function (result) {
                if (result == "用户名已经存在") {
                    $("#msg").html(result).css("color", "red");
                } else {
                    $("#msg").html(result).css("color", "green");
                    rst = true///////////////////////
                }
            },
            error: function () {
                alert("发生错误");
            }
        });

        return rst///////////////////////
    });
lgc8023 2014-09-16
  • 打赏
  • 举报
回复
lz点击事件换成onClick  $("#cateMgr").click(function () {//提交按钮触发事件                 if ($.trim($("#cateName").val()) == "") {                     $("#msg").html("用户名不能为空!").css("color", "red");                     return false;                 }                 $.ajax({                     url: "@Url.Action("CheckCateExists")",                     type: "POST",                     data: "categoryName=" + $("#cateName").val(),                     dataType: "text",                     success: function (result) {                         if (result == "用户名已经存在") {                             $("#msg").html(result).css("color", "red");                         } else {                             $("#msg").html(result).css("color", "green"); $("#cateMgr").submit();//form提交                             return true;                         }                     },                     error: function () {                         alert("发生错误");                     }                 });             });

52,797

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 Ajax
社区管理员
  • Ajax
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧