从阿贾克斯到爪哇脚本的返回值

我正在尝试检查数据库中是否已存在名称。但是我的Ajax没有返回值,老实说,甚至不确定Ajax是否正在运行。


这是我在php页面上的代码。


<input class="form-control" id="name" name="name" onblur="checkNameStatus()" />


<script>    

    function checkNameStatus(){

    //alert('Start of funtion');

    var name=$("#name").val();

    //alert("Name Input value is: "+name);

    $.ajax({

        type:'post',

            url:'<?php echo base_url() ?>assets/ajax/checkName.php?name='+name,

            success:function(msg){

            alert(msg);     

            }

     });

     //alert("End of function");

    }

</script>

使用警报,我可以判断该函数确实正在运行并接收名称输入的值。


然后是我的阿贾克斯


<?php


$hostname   = 'localhost';

$username   = 'root';

$password   = '123';

$dbname     = 'test_db';


function clean($string) {

   return preg_replace('/[^A-Za-z0-9\- .!@#$%&]/', '', $string);

}


$name= clean($_GET['name']);

$msg = "";


$conn=mysqli_connect($hostname,$username,$password,$dbname);


if (mysqli_connect_errno()){

    echo ("Failed to connect to MySQL: " . mysqli_connect_error());

}


$sql = "SELECT * FROM pattern where name = '$name';";


$check=mysqli_query($conn, $sql);

$count=mysqli_num_rows($check);


if($count!=0)

   {

     $msg = "A Schedule Pattern with the Name of $name already exists. If you continue to use this Name it will overwrite $name's current Data.";

     return $msg;

   } else {

    $msg = "Count check Failed"; 

    echo $msg;

   }



mysqli_close($con);


 ?>

如何从我的ajax接收$msg变量并将其返回到脚本,然后随后在警报中显示它?


慕妹3242003
浏览 74回答 1
1回答

函数式编程

我认为你必须改变这一点$check=mysql_query($sql);$count=mysql_num_rows($check);对此$check=mysqli_query($conn, $sql);$count=mysqli_num_rows($check);您正在同时使用mysql_和mysqli_这是错误的,这可能是它未能检查计数的原因,我还建议您在找不到名称的情况下发送错误消息。编辑,完整代码应为:(菲律宾比索):<?php$hostname&nbsp; &nbsp;= 'localhost';$username&nbsp; &nbsp;= 'root';$password&nbsp; &nbsp;= '123';$dbname&nbsp; &nbsp; &nbsp;= 'test_db';function clean($string) {&nbsp; &nbsp;return preg_replace('/[^A-Za-z0-9\- .!@#$%&]/', '', $string);}if(isset($_GET['name'])){$name= clean($_GET['name']);$msg = "";$conn=mysqli_connect($hostname,$username,$password,$dbname);if (mysqli_connect_errno()){&nbsp; &nbsp; echo ("Failed to connect to MySQL: " . mysqli_connect_error());}$sql = "SELECT * FROM pattern where `name` = '$name';";$check=mysqli_query($conn, $sql);$count=mysqli_num_rows($check);if($count!=0)&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp;$msg = "A Schedule Pattern with the Name of $name already exists. If you continue to use this Name it will overwrite $name's current Data.";&nbsp; &nbsp; &nbsp;echo $msg;&nbsp; &nbsp;} else {&nbsp; &nbsp; $msg = "Count check Failed";&nbsp;&nbsp; &nbsp; echo $msg;&nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;mysqli_close($conn);&nbsp; &nbsp;}&nbsp;&nbsp;?>
打开App,查看更多内容
随时随地看视频慕课网APP