Javascript 如何使用 AJAX 对选择选项执行 PHP 查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32389767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I execute a PHP query on select option choice using AJAX?
提问by triswill227
Okay I know this has been answered before (Execute PHP script on same page after selecting a dropdown list option using Ajax or JavaScript) but the answers weren't very helpful for someone who has never used AJAX before. How do I run a query like the one created if someone selects an option from the drop down?
好的,我知道之前已经回答过这个问题(使用 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);
?>
回答by Logan Wayne
First is, you have to trigger the AJAX request by using Javascript. But I'll be guiding you by using jQuery (a Javascript library).
首先,您必须使用 Javascript 触发 AJAX 请求。但我将通过使用 jQuery(一个 Javascript 库)来指导您。
Your HTML:
你的 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>
After that, download jQuery.
之后,下载jQuery。
Then lets do the script:
然后让我们做脚本:
<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>
Then lets create the get-data.php
which will receive the data sent through AJAX.
然后让我们创建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 */
}
You can check this example - JSfiddle.
您可以查看此示例 - JSfiddle。
回答by i.am
Check this simple tutorialHope this will help.
检查这个简单的教程希望这会有所帮助。
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
// getuser.php is seprate php file. q is parameter
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="txtHint"><b>Person info will be listed here...</b></div>
</body>
</html>
The getuser.php file
getuser.php 文件
<!DOCTYPE html>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
// don't use intval if your select value is not numberic
$q = $_GET['q'];
$con = mysqli_connect('localhost','peter','abc123','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
回答by guradio
var id="1";
$.ajax({
type: 'POST',
url: 'yourphppage',
dataType: "json",
data: {
idofrow:id
},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
This is a samle of ajax request you can use this and just change the other fields as need when the query is success you can retrieve that data in the success you can manipulate what data you want to use you can return json
,text
.
这是Ajax请求的samle你可以使用这个,只是改变其他领域需要查询的时候是成功的,你可以检索,在成功的数据,你可以操纵你想用就可以返回数据json
,text
。
In your php page you can retrieve the id as
在您的 php 页面中,您可以将 id 检索为
$id = ($_POST['idofrow']);
you can then you this id to select like this
你可以然后你这个id来选择这样
SELECT * FROM table where rowid = $id
and you can just echo the result.
你可以只回显结果。
for additional info just check on this documentation
有关其他信息,请查看此文档