警报框故障

时间:2017-08-19 20:22:32

标签: javascript php database search alert

我的脚本代码有问题。我有一个警告框,显示搜索结果,但问题是它显示的是先前的结果而不是当前的结果。它第一次给出null,然后通过给出前一个结果来工作。怎么了? 。谢谢提前

<?php
include_once('dbconnect.php');
if(isset($_POST['search'])){
    $q = $_POST['q'];
    $query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'"); 
//Replace table_name with your table name and `thing_to_search` with the column you want to search
    $count = mysqli_num_rows($query);
    if($count == "0" || $q == ""){
        $output = '<h2 style="color:white;">No player found!</h2>';
    }else{
                while($row = mysqli_fetch_array($query)){
        $s[] = $row['userIngame']; // Replace column_to_display with the column you want the results from
                $output = '<h2 style="color:white;">There are '.$count.' players </h2><br>';
                               } 

        }
}
echo json_encode($s);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html>


<head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
      <link rel="stylesheet" href="/resources/demos/style.css">
      <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
      <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<script>
           $(document).ready(function(){
               $("form").submit(function(){
                    var player = <?php echo json_encode($s); ?>;
                    alert("players : " + player);
    });
});
</script>

1 个答案:

答案 0 :(得分:0)

看一下PHP部件执行时会发生什么。第一次显示页面时,$ q为空。这就是为什么你的SQL不会返回任何结果。 $ output将设置为'<h2 style="color:white;">No player found!</h2>';,并且不会设置$ s []。这是在javascript标签内写入页面的内容......

<script> 
           $(document).ready(function(){
               $("form").submit(function(){
                    var player = null;
                    alert("players : " + player);
    });
});
</script>

这就是为什么,当您对表单进行求和时,警报显示为null。 第二次显示页面时,$ q有一个值,SQL调用填充$ s。现在脚本看起来像这样......

<script>
           $(document).ready(function(){
               $("form").submit(function(){
                    var player = "Some Playername";
                    alert("players : " + player);
    });
});
</script>

警报功能只会在您提交表单时执行,然后会在警告框中显示名称。但是当然,到那时,你期待下一个球员名字出现。