我编写了以下PHP代码,以从MySQL数据库检索多行,然后将其转换为JSON。该PHP文件名为 sql_json.php ,并通过jQuery使用$ .ajax方法进行调用。 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>
答案 0 :(得分:2)
您的表单中有一个操作,当您单击“提交”时,它将打开文件“ sql_json.php”,因此您的js代码不会将html呈现到页面上。您需要防止表单提交的默认行为。通过在您的javascript函数中添加e.preventDefault()。