一尘不染

如何使用AJAX对选择选项进行PHP查询?

mysql

好的,我知道这已经得到了回答(使用Ajax或JavaScript选择下拉列表选项后,在同一页面上执行PHP脚本),但是对于以前从未使用过AJAX的人来说,答案并不是很有帮助。如果有人从下拉列表中选择一个选项,如何运行类似创建的查询?

<head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<h3>Subject</h3>
<select name="allbooks" >
              <option value="none" ></option>
              <option value="allbooks" >All Books</option>
    </select>

<?php 
$query = "SELECT * FROM books" or die("Error in the consult.." . mysqli_error($connection)); 
    $books = $connection->query($query);
?>

阅读 331

收藏
2020-05-17

共1个答案

一尘不染

首先,您必须使用Javascript触发AJAX请求。但是,我将通过使用jQuery(一个Javascript库)指导您。

您的HTML:

<select name="allbooks" id="allbooks">
  <option value="none" ></option>
  <option value="allbooks" >All Books</option>
</select>
<div id="show">
  <!-- ITEMS TO BE DISPLAYED HERE -->
</div>

之后,下载jQuery

然后执行脚本:

<script src="jquery-1.9.1.min.js"></script> <!-- CHANGE THE JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
  $(document).ready(function(){ /* PREPARE THE SCRIPT */
    $("#allbooks").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
      var allbooks = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
      var dataString = "allbooks="+allbooks; /* STORE THAT TO A DATA STRING */

      $.ajax({ /* THEN THE AJAX CALL */
        type: "POST", /* TYPE OF METHOD TO USE TO PASS THE DATA */
        url: "get-data.php", /* PAGE WHERE WE WILL PASS THE DATA */
        data: dataString, /* THE DATA WE WILL BE PASSING */
        success: function(result){ /* GET THE TO BE RETURNED DATA */
          $("#show").html(result); /* THE RETURNED DATA WILL BE SHOWN IN THIS DIV */
        }
      });

    });
  });
</script>

然后让我们创建get-data.php,它将接收通过AJAX发送的数据。

if(!empty($_POST["allbooks"])){
  /* DO YOUR QUERY HERE AND GET THE OUTPUT YOU WANT */
  echo $output; /* PRINT THE OUTPUT YOU WANT, IT WILL BE RETURNED TO THE ORIGINAL PAGE */
}

您可以查看此示例JSfiddle

2020-05-17