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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵