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 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测