2 回答
TA贡献1848条经验 获得超2个赞
通过 jquery ajax 传递它会很棒。我根据您的要求为您重新编写了一个很好的插图。
假设您的表具有列id、用户名、名称、电子邮件等......或者您可以按如下方式创建表并插入其中进行测试
create table users_test(id int primary key auto_increment,username varchar(30),name varchar(30), email varchar(30));
插入测试
insert into users_test(username,name,email) values('nancy','nancy moore','nany@gmail.com');
insert into users_test(username,name,email) values('tony','tony moore','tony@gmail.com');
索引.html
<!doctype html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'test.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var id = response[i].id;
var username = response[i].username;
var name = response[i].name;
var email = response[i].email;
var tr_str = "<tr>" +
"<td align='center'>" + (i+1) + "</td>" +
"<td align='center'>" + username + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + email + "</td>" +
"</tr>";
$("#userTable tbody").append(tr_str);
}
}
});
});
</script>
</head>
<body>
<div class="container">
<table id="userTable" border="1" >
<thead>
<tr>
<th width="5%">S.no</th>
<th width="20%">Username</th>
<th width="20%">Name</th>
<th width="30%">Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</body>
</html>
测试文件
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "you db here"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection to db failed ");
}
$test = array();
$query = "SELECT * FROM users_test ORDER BY id";
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$username = $row['username'];
$name = $row['name'];
$email = $row['email'];
$test[] = array("id" => $id,
"username" => $username,
"name" => $name,
"email" => $email);
}
// Encoding array in JSON format
echo json_encode($test);
TA贡献1828条经验 获得超4个赞
好吧,我尝试了此代码并使用了价值
<?php
while($row = $result->fetch_assoc())
{
$tmp[] = $row;
}
$test = json_encode($tmp);
?>
<script type="text/javascript">
var test = <?php echo $test; ?>;
document.write(JSON.stringify(test));
</script>
My data output : [{"id":"1","name":"ranbir","city":"delhi","age":"35"},{"id":"2","name":"sonu","city":"punjab","age":"40"},{"id":"3","name":"ranbir","city":"delhi","age":"35"},{"id":"4","name":"sonu","city":"punjab","age":"40"}]
添加回答
举报