什么是创建一个Ajax用户名验证处理的最佳方法是什么? [英] What's the best method to create an AJAX user name validation handler?

查看:94
本文介绍了什么是创建一个Ajax用户名验证处理的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个社交网站,以及提高前端有一些吐和波兰。

I'm developing a social networking website, and improving the front-end with some spit and polish.

一个我实施的改善是一个AJAX验证聊天名。该设置是这样的:

One of the improvements I'm implementing is an AJAX validator for chat names. The set-up is this:

观众首长注册页面,访问者类型自己想要的聊天名到字段。虽然打字,用户得到即时的反馈到聊天名是否已被使用,含有非法字符,长度错误等。

Visitor heads to registration page and the visitor types their desired chat name into a field. Whilst typing, the user is given instant feedback as to whether that chat name is already in use, contains illegal characters, is the wrong length etc.

我已经得到了这个工作我已经建立了一个简单的PHP脚本来充当绑定到我输入的的onkeyup 模糊事件。然而,每个请求涉及其不能很好数据库查询。

I've got this working: I've set up a simple PHP script to act as an AJAX handler that's bound to my input's onkeyup and blur events. However, each request involves a database query which can't be good.

我的问题是:我怎么能简化这一点?当然,在每个的onkeyup 模糊数据库查询是不是一个好主意?

My question is: how can I streamline this? Surely a database query upon each onkeyup or blur is not a good idea?

推荐答案

我推荐以下(基于时间的)战略:

I recommend the following (time-based) strategy:

  1. KEYUP火灾
  2. 取消超时(如果是在同时运行)
  3. 在开始一个新的超时(500 - 1000毫秒)
  4. 请请求时发生超时

这样,你可以做一个请求,每次用户停止键入至少500 - 1000毫秒。这样可以节省您在用户仍在键入一些要求。可以立即开始请求时的模糊,事件被触发,由于用户未输入任何更明显。

This way you can do a request everytime the user stops typing for at least 500 - 1000 ms. This saves you some requests while the user is still typing. You can start the request immediately when the blur-event is fired, since the user is not typing any more, obviously.

为例(使用jQuery)与500毫秒:

Example (using jQuery) with 500 ms:

var timeout = null;

var stopTimeout = function () {
    // step 2: stop running timeout
    if (timeout !== null) {
        clearTimeout(timeout);
        timeout = null;
    }
};

var doRequest = function () {
    // step 4: do request
};

// step 1: event fires
$('input').keyup(function () {
    stopTimeout();
    // step 3: start new timeout
    timeout = setTimeout(doRequest, 500);
}).blur(function () {
    stopTimeout();
    doRequest();
});

正如其他人指出,检查无效字符等,应做的客户端以及服务器端,因为你不能信任客户端。

As others stated, checking for invalid characters, etc. should be done client-side as well as server-side, since you cannot trust the client.

这篇关于什么是创建一个Ajax用户名验证处理的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆