我想要一些javascript + ajax来检查用户名的可用性.我有一些麻烦......
让我们想象一下当我们在模糊事件上检查用户名可用性时的情况.
如果我们得到这样的情景怎么办?
telling user that username is available, but it not (because we're telling about "kir", but not "kirA").我该怎么做才能避免这种情况?使用某种随机生成的令牌来检查答案的有效性?
谢谢
您应该在创建新XHR时使用XHR.
var ongoingRequest = null;
function test() {
if(ongoingRequest != null) {
ongoingRequest.abort();
}
ongoingRequest = $.ajax( ... );
}
Run Code Online (Sandbox Code Playgroud)
当您收到响应时,您可以添加额外的功能以再次验证:
$.ajax({
...
data: { query: query },
success: (function(q) {
return function(result) {
if( $('#myTxt').val() != q) {
// the textbox value is not the same as the query was
// at the time of creating this response!
return false;
}
...
}
})(query)
});
Run Code Online (Sandbox Code Playgroud)
您需要在XHR请求对象和它包含的用户名查询之间进行某种映射.或者在服务器对AJAX查询的响应中,也包括用户名.回复可能如下:
{
username: "kir",
available: false
}
Run Code Online (Sandbox Code Playgroud)
在回调中,验证当前文本框值是否与返回的用户名相同.如果是,则显示错误,否则忽略该响应.
| 归档时间: |
|
| 查看次数: |
2156 次 |
| 最近记录: |