簡體   English   中英

為什么 PHP AJAX 只能從第二次點擊開始工作?

[英]Why does PHP AJAX work as from second click only?

PHP 和 AJAX 的新手。

我制作了一個基本頁面,當我單擊一個按鈕時,一個 php 頁面將連接到數據庫並返回年齡為 45 歲的人的姓名(發送時已包含在 url 中)。

我唯一的問題是,它只在我第二次單擊按鈕時起作用。 請幫忙?

我的 ajax.html 和 ajax-example.php 代碼如下:

<!DOCTYPE html>
<html>
   <body>

    <script type="text/javascript">
        ajaxRequest = new XMLHttpRequest();
        function ajaxFunction() {
            ajaxRequest.onreadystatechange = reaction();
            ajaxRequest.open("GET","ajax-example.php?age=45", true);
            ajaxRequest.send(null);
        }

        function reaction() {
            if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
               alert(ajaxRequest.responseText);
            }
        }
     </script>

      <button onclick="ajaxFunction();">Click me</button>

   </body>
</html>

<?php
   $server = "localhost";
   $user = "root";
   $password = "";
   $db = "ajaxtrial";

  $conn = mysqli_connect($server,$user,$password,$db);

  if (!$conn) {
      die('Failure to connect!');
  }

  $age = $_GET['age'];

  $sql = "SELECT name FROM ajax_example WHERE age =".$age;

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

  while ($row = mysqli_fetch_assoc($result)) {
   $display = "The name is ".$row['name'];
  }

  echo $display;
?>

刪除您分配給onreadystatechangereaction方法的括號。

<script type="text/javascript">
    ajaxRequest = new XMLHttpRequest();
    function ajaxFunction() {
        ajaxRequest.onreadystatechange = reaction;
        ajaxRequest.open("GET","ajax-example.php?age=45", true);
        ajaxRequest.send(null);
    }

    function reaction() {
        if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
           alert(ajaxRequest.responseText);
        }
    }
 </script>

或者您可以將匿名函數初始化為onreadystatechange

 <script type="text/javascript">
    ajaxRequest = new XMLHttpRequest();
    function ajaxFunction() {
        ajaxRequest.onreadystatechange = function(){
           if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
               alert(ajaxRequest.responseText);
           }
        }
        ajaxRequest.open("GET","ajax-example.php?age=45", true);
        ajaxRequest.send(null);
    }
 </script>

我希望這對你有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM