使用ajax检查用户名可用性

时间:2015-04-05 15:57:29

标签: php jquery ajax

我想检查用户名是否可用。

我正在关注此事:http://phppot.com/demo/live-username-availability-check-using-php-and-jquery-ajax/

我一直收到错误警告,怎么回事?

Ajax调用

function checkAvailability() {
    $("#loaderIcon").show();
    $.ajax({
        url: "check_availability.php",
        data:'username='+$("#username").val(),
        type: "POST",
        success:function(data){
            $("#user-availability-status").html(data);
            $("#loaderIcon").hide();
        },
        error:function (){alert("error");}
    });
}

服务器端:

<?php
/* this is check_availability.php  file */
  $con=  mysqli_connect('localhost','root','password','user') or die(mysqli_error());
  if($con)  { echo 'connected';}
  $username=mysqli_real_escape_string($con, $_POST['username']);
  $query="SELECT * FROM username_list WHERE     username='$username' ";
  $result=  mysqli_query($con,$query);
  $rowCount=  mysqli_num_rows($result);
  if($rowCount>0) {
      echo "<span class='status-not-available'> Not Available.</span>";
  } else {
      echo "<span class='status-available'> Username Available.</span>";
  }
?>

1 个答案:

答案 0 :(得分:1)

如果没有提到的更多信息和测试用例,很难确定最新情况。

以下是您的情况可能发生的情况:ajax调用失败,我可以肯定地说,因为错误函数执行

  

错误 - 类型:功能(jqXHR jqXHR,String textStatus,String errorThrown)   请求失败时要调用的函数。该函数接收三个参数:jqXHR(在jQuery 1.4.x,XMLHttpRequest中)对象,描述发生的错误类型的字符串和可选的异常对象(如果发生)。第二个参数的可能值(除了null)是“timeout”,“error”,“abort”和“parsererror”。发生HTTP错误时,errorThrown会收到HTTP状态的文本部分,例如“Not Found”或“Internal Server Error”。从jQuery 1.5开始,错误设置可以接受一系列函数。每个函数将依次调用。注意:不会为跨域脚本和跨域JSONP请求调用此处理程序。这是一个

问题可能是目标无法访问 - 更改代码然后打开控制台以查看最新情况。我还将你的ajax调用更改为更好的格式:

function checkAvailability() {
   var username_tocheck = $("#username").val(); //Probably you want to validate it before you send
   $.ajax({
           url: "check_availability.php", // Try full url too
           data: { username :  username_tocheck },
           method: "POST",  //  POST | GET
           dataType: "html", // xml,json,script,html
           beforeSend: function() {
                 $("#loaderIcon").show();
           },
           success:function(data){
                 $("#user-availability-status").html(data);
                 $("#loaderIcon").hide();
           },
           error:function ( jqXHR, textStatus ){
                alert("error: " + textStatus);
                console.log("error: " + textStatus);
           }
   });
}

如你所见,我做了很多改变:

  1. 将数据更改为对象。
  2. type更改为method
  3. 添加dataType - 设置为您需要的任何内容。
  4. 将加载程序图标移至beforeSend处理程序 - 您可能更喜欢将其隐藏在always处理程序中。
  5. 暴露了实际错误。
  6. 玩得开心。

相关问题