我正在开发一个小型项目,以根据所选的复选框显示从数据库查询的值。 我遇到过很多帖子:可以使用 ajax/jquery 来完成。 我不知道如何使用ajax。 请帮助我,我陷入了最终警报窗口输出。
这是我的主要 test.php
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>--</title>
<script>
function checkAddress()
{
if (document.querySelector('form[name="frmUser"] input[type="checkbox"]:checked')) {
//alert("Success! (form would be submitted here)");
var $temp = <?php include 'alert.php';?>
//alert("Success! (form would be submitted here)");
alert($temp)
document.frmUser.action = "test.php";
document.frmUser.submit();
} else {
alert("Pl select checkbox which You wish to Update ");
}
}
</script>
</head>
<body >
<h1 style="text-align:center;"></h1>
<?php
// php populate html table from mysql database
$conn = mysqli_connect("localhost","root","11111111");
mysqli_select_db($conn, "test");
$result = mysqli_query($conn,"SELECT * FROM inputs ORDER BY userId DESC");
?>
<div class="form-style-1">
<form name="frmUser" method="post" action="">
<div style="width:1200px;">
<table style="text-align:center;"border="0" cellpadding="10" cellspacing="1" width="1200" class="tblListForm" align="center">
<tr class="listheader">
<td></td>
<td>SN</td>
<th>Domain</th>
<th>department</th>
<th></th>
</tr>
<?php
$i=0;
$j=1;
while($row = mysqli_fetch_array($result)) {
if($i%2==0){
$classname="evenRow";
} else {
$classname="oddRow";
}
?>
<tr class="<?php if(isset($classname)) {
echo $classname;
}?>">
<td><input type="checkbox" name="users[]" value="<?php echo $row["userId"]; ?>" ></td>
<td><?php echo $row["userId"]; ?></td>
<td><?php echo $row["department"]; ?></td>
<th colspan="4"><input type="button" name="update" class="button" value="Apply" onClick="checkAddress(this);" /></th></tr>
<?php
$i++;
$j=$i+1;
}
$conn->close();
?>
</table>
</div>
</form>
</div>
</body>
</html>
下面是我的alert.php
<?php
$servername = "localhost";
$username = "root";
$password = "11111111";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$rowCount = count($_POST['users']);
//echo "The rowcount is ".$rowCount."";
$queried_name;
for($i=0;$i<$rowCount;$i++) {
$num_var= " ";
$num_var = mysqli_real_escape_string($conn,$_POST['users'][$i]);
//echo "The numvar is ".$num_var."";
$result = mysqli_query($conn, "SELECT * FROM inputs WHERE userId='".$num_var."'");
if (!$result) {
echo 'MySQL Error: ' . mysqli_error($conn);
exit;
}
while($row[$i]= mysqli_fetch_array($result)) {
$queried_name = $row[$i]['department'];
return $queried_name;
echo 'alert("Please Use below department.' .$queried_name.'")';
}}}
$conn->close();
?>
最佳答案
如果您使用 jQuery,您可以利用它们内置的 ajax功能。如果您仅限于“普通”javascript,下面是我通常用于 AJAX 调用的函数:
function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
var xmlHttpRequest = new XMLHttpRequest();
var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
xmlHttpRequest.open(method, url, async);
xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
xmlHttpRequest.send(param);
if(!async) { callback(xmlHttpRequest); }
}
使用示例:
ajaxQuery('alert.php', 'GET', null, true, function(r) {
alert(r.responseText);
}, function() { alert('Something went wrong.'); });
当然,如果alert.php
执行任何复杂的任务,它就必须接受参数,然后你可以引用alert.php?parameter0=something¶meter1=something
而不仅仅是alert.php
。
我建议在这个阶段做一些更简单的事情,因为您将 php 与 javascript 混淆了,并且您似乎不太明白 include
语句在 php 文件中的具体作用。它不会返回脚本的输出 - 它所做的相当于将整个 php 文件回显到另一个文件中!您正在将 alert.php
的内容从 javascript 分配给可怜的旧 alert()
。在这个阶段,我个人会将项目分成不同的语言(纯粹用 javascript、纯粹用 php 等),并在我准备好时开始将它们混合在一起。
您不需要 JavaScript 来为表单的 action
属性赋值。这可以在 form
标记本身内完成。
如果需要进一步解释,请告诉我。
更新:以下是您请求的代码示例。我浏览了你的代码并“修复”了它。重要提示:您应该选择一个格式标准并坚持它。示例:
- 您以 2 种不同的方式在 2 个不同的位置连接到数据库,您应该有一个包含在所有相关 php 中的数据库连接文件。
- 您的引号有时是单引号,有时是双引号,我个人只在必要或方便时使用双引号(SQL 查询、包含特殊字符的字符串,例如
"\n"
)。 - 缩进不遵循任何特定逻辑,空行随处可见;格式化代码非常重要,以便您和其他人可以在几个月内阅读它,而没有人记得它到底是关于什么的。
- 在你的 test.php 中,你有一个表嵌套在 div 中,嵌套在表单中,嵌套在 div 中 - 这几乎没有必要。
- 为什么存在空的
td
和th
标签? - 您应该密切注意 HTML 标记的关闭方式:我注意到一些
">
和"/>
。当然,浏览器不会关心大部分内容,但代码的可读性会受到影响。 - 据我所知,HTML 属性始终为小写(
onClick
应该是onclick
等)。 - 你的 table 布局很奇怪,但我没碰过。我不知道为什么每一行都有一个
colspan="4"
元素。 - 方法名称(
GET
和POST
)应始终为大写(XHTML 中的情况除外)。
1) 测试.php
<!DOCTYPE html>
<!--[if lt IE 7]><html class="ie ie6" lang="en"><![endif]-->
<!--[if IE 7]><html class="ie ie7" lang="en"><![endif]-->
<!--[if IE 8]><html class="ie ie8" lang="en"><![endif]-->
<!--[if (gte IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>--</title>
<script>
function ajaxQuery(url, method, param, async, onsuccess, onfailure) {
var xmlHttpRequest = new XMLHttpRequest();
var callback = function(r) { r.status==200 ? (typeof(onsuccess)=='function' && onsuccess(r)) : (typeof(onfailure)=='function' && onfailure(r)); };
if(async) { xmlHttpRequest.onreadystatechange = function() { if(xmlHttpRequest.readyState==4) { callback(xmlHttpRequest); } } }
xmlHttpRequest.open(method, url, async);
xmlHttpRequest.setRequestHeader('X-REQUESTED-WITH', 'XMLHttpRequest');
if(method == 'POST') { xmlHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); }
xmlHttpRequest.send(param);
if(!async) { callback(xmlHttpRequest); }
}
function checkAddress(e) {
var checkbox = e.target.parentNode.parentNode.querySelector('[type="checkbox"]');
if(checkbox) {
ajaxQuery('alert.php', 'POST', 'users[]='+checkbox.value, true, function(request) {
alert(request.responseText);
}, function() { alert('Shiver me timbers!'); });
} else {
alert('Please select a checkbox to update.');
}
}
</script>
</head>
<body>
<h1 style="text-align: center;"></h1>
<?php
$conn = mysqli_connect('localhost', 'root', '11111111');
mysqli_select_db($conn, 'test');
$result = mysqli_query($conn, "SELECT * FROM inputs ORDER BY userId DESC");
?>
<div class="form-style-1">
<form name="frmUser" method="POST" action="test.php">
<div style="width: 1200px;">
<table style="text-align: center;" border="0" cellpadding="10" cellspacing="1" width="1200" class="tblListForm" align="center">
<tr class="listheader">
<td></td>
<td>SN</td>
<th>Domain</th>
<th>Department</th>
<th></th>
</tr>
<?php
$i=0;
$j=1;
while($row = mysqli_fetch_array($result)) {
$classname = $i%2==0 ? 'evenRow' : 'oddRow';
?>
<tr<?php if(isset($classname)) { echo ' class="'.$classname.'"'; } ?>>
<td>
<input type="checkbox" name="users[]" value="<?=$row["userId"];?>">
</td>
<td><?=$row["userId"];?></td>
<td><?=$row["department"];?></td>
<th colspan="4">
<input type="button" name="update" class="button" value="Apply" onclick="javascript: checkAddress(event);">
</th>
</tr>
<?php
$i++;
$j=$i+1;
}
$conn->close();
?>
</table>
</div>
</form>
</div>
</body>
</html>
2)alert.php
<?php
$servername = 'localhost';
$username = 'root';
$password = '11111111';
$dbname = 'test';
$conn = new mysqli($servername, $username, $password, $dbname); // Create connection
if($conn->connect_error) { die('Connection failed: '.$conn->connect_error); } // Check connection
if(isset($_POST['submit'])){
$rowCount = count($_POST['users']);
$num_var= '';
$queried_name = '';
for($i=0; $i<$rowCount; $i++) {
$num_var = mysqli_real_escape_string($conn, $_POST['users'][$i]);
$result = mysqli_query($conn, "SELECT * FROM inputs WHERE userId='".$num_var."'");
if(!$result) { die('MySQL Error: '.mysqli_error($conn)); }
while($row[$i]= mysqli_fetch_array($result)) {
$queried_name = $row[$i]['department'];
echo "Please refer to the following department: $queried_name\n";
}
}
}
$conn->close();
?>
关于javascript - 警报在不使用 Ajax 的情况下从数据库查询的 java 脚本中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43634908/