目前,我正在调整注册页面以使用Ajax/jQuery.它在简单的阶段,只需要用户名和密码.
我想使用jQuery告诉用户用户名文本框中的当前条目是无效还是已被采用.如果满足条件,则div namemsg将添加文本并执行fadeIn事件.
页面加载时禁用提交按钮,并在通过验证时启用按钮.为此,我有以下ajax请求来处理用户名验证
$("#username").keyup(function(){
//get current value
thisVal = $(this).val();
//execute request to see if current val exists in database
$.ajax({
type: "GET",
url: "includes/phpscripts.php?action=checkUser",
data: {username:thisVal},
success: function(data){
//if username is already taken, show warning and disable submit button
if (data == 'true'){
$("#namemsg").text("Username is already taken");
$("#namemsg").fadeIn(100);
$("#submit").attr('disabled', 'disabled');
}
//otherwise, possible valid username
else if (data == 'false'){
//check if username is of the proper length. If not, display
//error and disable submit button
if ($(this).val().length < 5){
$("#namemsg").text("Invalid Username");
$("#namemsg").fadeIn(100);
$("#submit").attr('disabled', 'disabled');
}
//valid username, enable submit button and hide any error messages
else {
$("#namemsg").hide();
$("#submit").removeAttr("disabled");
}
}
}
});
return false;
});
Run Code Online (Sandbox Code Playgroud)
我的问题是请求从服务器获取propper值,但是firebug抱怨elem.nodeName在jquery 1.7.2的第2368行未定义.那条线是
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
Run Code Online (Sandbox Code Playgroud)
当我设置断点时if (elem),elem有值
nodeName : INPUT
type : text
Run Code Online (Sandbox Code Playgroud)
并hooks返回undefined.这是Firefox特有的问题,我的代码或jQuery的问题?此外,有一个解决方法吗?
在你的success处理程序中,this是jqXHR请求,而不是$("#username")字段,因此$(this).val()是错误的.
当你有缓存的值时,最好使用thisVal而不是$(this).val(),但一般来说,解决这个问题的方法是设置context元素的选项;
$.ajax({
context: this,
type: 'GET',
// etc
});
Run Code Online (Sandbox Code Playgroud)
您可以在jQuery.ajax()页面上查看此方法的文档(搜索"上下文").
另一种方法是将this指向元素的方法设置为另一个变量;
$("#username").keyup(function(){
var that = this;
$.ajax({
type: "GET",
url: "includes/phpscripts.php?action=checkUser",
data: {username:thisVal},
success: function(data){
// use `that` and `$(that)` in here
}
});
return false;
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8307 次 |
| 最近记录: |