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.

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

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?