我有一段代码,用于通过 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/