javascript - 如果语句不起作用,jQuery/AJAX 成功函数?

标签 javascript jquery mysql ajax if-statement

我有一段代码,用于通过 jQuery AJAX 调用检查所需的用户名是否可用:

function check_username()
{

    // Set user_name to the current value of input #new_user_name
    var user_name = document.getElementById('new_user_name').value;

    // Ajax to check availability of username
    $.ajax({
        url: '_check_username.php',
        type: 'post',
        data: { 'user_name': user_name },
        success: function(data) {   

            var does_it_pass_or_fail = data;

            if ( does_it_pass_or_fail === "fail" )
            {
                alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail ); );
            }
            else
            {
                alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail ); );
            }
        }, error: function() {
           // Not sure what to put here...
        }
    });

}

脚本按预期工作——我在 _check_username.php 上检查 MySQL 数据库,如果名称可用,则成功返回“通过”,如果名称已被占用,则成功返回“失败”,并将其存储在 JS 中变量 does_it_pass_or_fail。

但是,无论 does_it_pass_or_fail 是否包含“pass”或“fail”,我只会收到“该用户名可用!”的响应

所以,AJAX/PHP/MySQL 部分似乎工作正常,但是这个简单的 JavaScript if 语句让我难住了!

最佳答案

尝试使用这个:您的代码中存在一些接近alert.try日志错误的语法错误。

function check_username()
{

    // Set user_name to the current value of input #new_user_name
    var user_name = document.getElementById('new_user_name').value;

    // Ajax to check availability of username
    $.ajax({
        url: '_check_username.php',
        type: 'post',
        data: { 'user_name': user_name },
        success: function(data) {   

            var does_it_pass_or_fail = data;
            console.log(data);
            if ( does_it_pass_or_fail === "fail" )
            {
                alert( "Sorry, the username already exists. does_it_pass_or_fail = " + does_it_pass_or_fail );
            }
            else
            {
                alert( "That username is available! does_it_pass_or_fail = " + does_it_pass_or_fail );
            }
        }, error: function(erro) {
          console.log(error);
        }
    });

}

关于javascript - 如果语句不起作用,jQuery/AJAX 成功函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27465248/

相关文章:

javascript - jquery .html()函数没有给出数据属性设置值

javascript - jQuery 验证语法错误,无法识别的表达式 : label[for=]

php - MySql 将按日期分组的数据行转换为动态列

MySQL 2 个表 UNION

mysql - 如何从MySQL中的每个类别中获取随机记录?

javascript - 是否可以在 Javascript 中创建带有前缀的 XML 节点?

javascript - JS |Xss防御题

javascript - 在 get 调用中设置后变量仍保持未定义状态

javascript - JQuery向未知的div id添加点击事件

javascript - 使用 jQuery/plain JS 检测 webOS 平板电脑的最佳方法是什么