繁体   English   中英

使用ajax检查用户名可用性

[英]Check username availability using 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>";
  }
?>

没有提到的更多信息和测试用例,很难确定发生了什么。

这可能是您遇到的情况:ajax调用失败,可以肯定地说,因为执行了错误函数

错误 -类型:Function(jqXHR jqXHR,字符串textStatus,字符串errorThrown)的函数,如果请求不被调用。 该函数接收三个参数:jqXHR对象(在jQuery 1.4.x中为XMLHttpRequest),一个描述发生错误的类型的字符串,以及一个可选的异常对象(如果发生)。 第二个参数(除null外)的可能值为“超时”,“错误”,“中止”和“ parsererror”。 发生HTTP错误时,errorThrown会接收HTTP状态的文本部分,例如“未找到”或“内部服务器错误”。 从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. 暴露出实际错误。

祝您探索愉快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM