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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?