dpc46827 2011-09-19 12:37
浏览 20
已采纳

Jquery和ajax,我的用户名检查功能?

I have written this ajax request for username checking...

function check_username() {
    var username = $("#username").val();
    $('.loading').fadeIn().delay(100);
    $.post("ajax.php", {
        username: $('#username').val(),
    }, function (response) {
        $('.error, .success').hide();
        setTimeout(function () {
            $('.loading').hide();
            finishAjax('username', response);
        }, 1000);
    });
    return false;
}

function finishAjax(id, response) {
    $('#' + id).after(response).fadeIn(1000);
}

It all works fine just a couple of questions,

  1. Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.

  2. Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.

  3. Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.

  4. Is there a way to make the ajax request with every character the user enters?

My ajax php is as follows...

<?php

require('dbc.php');

if (isset($_REQUEST['username'])) {

  $q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
  $q -> execute(array($_REQUEST['username']));

  if (strlen($_REQUEST['username']) < 3) {
    echo '<div class="error">Has to be at least 3 characters</div>';
  } 
  elseif ($q -> rowCount() > 0) {
    echo '<div class="error">Username already taken</div>';
  } 
  else {
    echo '<div class="success">Username available</div>';
  }
}

?>
  • 写回答

1条回答 默认 最新

  • douzha5990 2011-09-19 13:59
    关注

    To answer 1 & 2. I would turn it into a plugin and do something along these lines.

    $.fn.checkValid = function(options)
    {
        var response = function(response) {
            var setClass = '';
            var $span = $(this).data('checkValidTip');
            if ($span)
            {
                $span.remove();
            }
    
            if (response === undefined) return;
    
            setClass = (response.valid ? 'valid' : 'invalid');
    
            var $span = $('<span>' + response.msg + '</span>');
            $(this)
                .data('checkValidTip', $span)
                .after($span);
    
            $span.hide()
                 .fadeIn(1000)[0]
                 .className = setClass;
        };
    
    
        var ajaxOptions = {
            type: 'GET',
            url: 'ajax.php',
            success: response,
            dataType: 'json'
        };
    
        this.each(function() {
    
            var that = this;
            var ajaxRequest = ajaxOptions;
            ajaxRequest.data = {};
            ajaxRequest.data[options.key] = this.value;
            ajaxRequest.context = that
    
            $.ajax(ajaxRequest);
        });
    };
    

    Usage

    $('#username, #email').blur(function() {
        $(this).checkValid({ key: this.id });
    });
    

    PHP changes

    You should make your PHP function return a JSON, instead of HTML i.e.

    <?php
       // Do your sql statements here, decide if input is valid or not
    
       $arr = array('valid' => $is_valid,
                    'msg'   => $error_or_good_msg
                   );
    
      echo json_encode($arr);
    
     /* For example will output:
       {
          "valid": "false",
          "msg": "<b>Error: Must be at least 2 characters</b>"
        }
      Which can be read directly as response.valid
      or response.msg from within response() function
     */
    

    To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:

    var validations = {
        username: {
          min_chars: 4,
          max_chars: 10,
          valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
        },
    
        email: {
           regex: /./ //your magic regex here
      }
    };
    

    jsFiddle

    http://jsfiddle.net/sqZfp/2/

    To answer 4, just change the event as above from .blur to .keyup should do the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯IOA系统怎么在文件夹里修改办公网络的连接
  • ¥15 filenotfounderror:文件是存在的,权限也给了,但还一直报错
  • ¥15 关于远程桌面的鼠标位置转换
  • ¥15 MATLAB和mosek的求解问题
  • ¥20 修改中兴光猫sn的时候提示失败
  • ¥15 java大作业爬取网页
  • ¥15 怎么获取欧易的btc永续合约和交割合约的5m级的历史数据用来回测套利策略?
  • ¥15 有没有办法利用libusb读取usb设备数据
  • ¥15 为什么openeluer里面按不了python3呢?
  • ¥15 关于#matlab#的问题:训练序列与输入层维度不一样