Ajax 和 MySQL 检查用户名是否已被占用的问题

我进行了测试,并确认我能够通过提醒函数 checkusername 中的值来从输入框中获取值。我还为查询单独测试了 php 文件,并且它有效。我真的认为问题是将值从我的第一个页面转移到另一个页面(thoughtverifier.php)或从“thoughtverifier.php”获取值


<script>

 function checkusername(puser){

   var AJAXObject;

   if (puser == "" )

  return ;


   if (window.XMLHttpRequest) 

 AJAXObject =new XMLHttpRequest();

   else 

   AJAXObject =new ActiveXObject("Microsoft.XMLHttp");

   AJAXObject.onreadystatechange= function(){

   if (AJAXObject.readyState ==4 && AJAXObject.status == 200) {

      document.getElementById('txtuser').innerHTML=AJAXObject.responseText

    }


    AJAXObject.open("GET","thoughtverifier.php?puse="+puser,true);

    AJAXObject.send();

  }

</script>

和 HTML 代码-


    <Form method ="post" name="regform" id ="regform" action="thoughtshomepage.php">


        <table class="alligm">

            <tr>

                <td>Username</td>

                <td><input type="text" name="txtuser" onchange="checkusername(this.value)"></td>

            </tr>

        </table>

    </Form>

和涉及的 PHP - 我正确连接到我的 SQL 和其余的


        $q = $_GET['puse'];//i have doubt here


        $strSQL =" SELECT * FROM `tableuser` WHERE username = '$q'" ;


        mysqli_query($con,$strSQL) or die(mysqli_error($con));

        $result = mysqli_query($con,$strSQL);

        $rowcount=mysqli_num_rows($result);

        if ($rowcount > 0) {

            echo "user exists";

        }

        else {

            echo "no";

        }

        mysqli_close($con);

    ?>


茅侃侃
浏览 204回答 3
3回答

偶然的你

您可以使用 jquery 进行 ajax 调用,这很简单,代码量也更少。你可以试试这个:$.get('/thoughtverifier.php?puse='+puser,&nbsp; function (data, textStatus, jqXHR) {&nbsp;&nbsp;&nbsp; if (data) {&nbsp; &nbsp; document.getElementById('txtuser').innerHTML=data&nbsp; }});

隔江千里

您没有 id 为“txtuser”的元素 document.getElementById('txtuser').innerHTML,所以也许您可以将 html 编辑为:<Form method ="post" name="regform" id ="regform" action="thoughtshomepage.php">&nbsp; &nbsp; <table class="alligm">&nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>Username</td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="text" name="txtuser" onchange="checkusername(this.value)">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span id="txtuser"></span>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </td>&nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; </table></Form>

开满天机

尝试这个$(function() {&nbsp; $("#regform").on("submit",function(e) {&nbsp; &nbsp; e.preventDefault(); // stop submission&nbsp; &nbsp; $.get(this.action+"?puse="+encodeURIComponent($("[name=txtuser]").val()),function(result) {&nbsp; &nbsp; &nbsp; $("[name=txtuser]").closest("tr").find("td").html(result==="no"?"User name OK":"User name taken");&nbsp; &nbsp; })&nbsp; });});并在您的服务器上使用解码还测试一下,如果你打电话,你会得到什么yourserver.com/thoughtshomepage.php?puse=exsting%20user
打开App,查看更多内容
随时随地看视频慕课网APP