我编写了以下PHP代码来从MySQL数据库中检索多行,然后将其转换为JSON。这个PHP文件名为sql_json.php,使用方法$ .ajax通过jQuery调用。 jQuery代码位于文件jquery_fetch.js中。最后我想在HTML文件json_search_user.html中显示它。从MySQL检索工作正常。但是jQuery代码不起作用,因此它无法显示编码的JSON。
PHP代码:(sql_json.php)
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/php_revision/dbase.php'); //dbase.php contains dtabase parameters like servername, username,password etc.
$conn=mysqli_connect($server,$username,$password,$db_name) or die('Connection to database failed');
if($conn){
$sql="SELECT FNAME,LNAME,DEPT,MOBILE_NO FROM USER WHERE ROLE=?" ;
$stmt=mysqli_prepare($conn,$sql);
mysqli_stmt_bind_param($stmt,"s",$role);
$role=$_POST['role'];
if(mysqli_stmt_execute($stmt)){
$result=mysqli_stmt_get_result($stmt);
$json= array();
$data_array=array();
while($row=mysqli_fetch_assoc($result)){
$data_array['FNAME']=$row['FNAME'];
$data_array['LNAME']=$row['LNAME'];
$data_array['DEPT']=$row['DEPT'];
$data_array['MOBILE_NO']=$row['MOBILE_NO'];
array_push($json,$data_array);
}
echo json_encode($json);
}
mysqli_stmt_close($stmt);
}
else{
echo json_encode({"Status" : "No results found"});
}
?>
jQuery代码:(jquery_fetch.js)
$(document).ready(function() {
$('#myForm').on('submit',function(e){
var role= $('#role').val();
$.ajax({
url:"sql_json.php",
type: "POST",
dataType: "JSON",
data:{role : role} ,
success: function(data){
var response= JSON.parse(data);
var genHtml='<table><tbody>';
for(var i=0;i<response.length;i++)
{
genHtml += '<tr><td>' + response[i].FNAME + '' + response[i].LNAME + '</td><td>' + response[i].DEPT + '</td><td>' + response[i].MOBILE_NO + '</td></tr>';
}
genHtml += '</tbody></table>';
$('#search_result').html(genHtml);
}
});
});
});
HTML文件(json_search_user.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search User </title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256- FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript" src="jquery_fetch.js"></script>
</head>
<body>
<form method="POST" action="sql_json.php" id="myForm">
<label for="role">Select Role :</label>
<select id="role" name="role" required>
<option disabled selected>Select</option>
<option value="Author">Author</option>
<option value="Publisher">Publisher</option>
<option value="Admin">Admin</option>
</select>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
<div id="search_result"></div>
</form>
</body>
</html>
您在表单中有一个操作,当您单击提交时,它将打开文件'sql_json.php',因此您的js代码不会将html呈现给页面。您需要阻止表单提交的默认行为。在你的javascript函数中添加e.preventDefault()。