使用Ajax代码在表中显示数组值可以通过以下步骤实现:
<!DOCTYPE html>
<html>
<head>
<title>Ajax表格显示数组值</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<table id="arrayTable">
<thead>
<tr>
<th>数组值</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script>
$(document).ready(function() {
// 使用Ajax获取数组值并显示在表格中
$.ajax({
url: 'get_array_values.php', // 替换为获取数组值的后端接口地址
type: 'GET',
dataType: 'json',
success: function(response) {
// 清空表格内容
$('#arrayTable tbody').empty();
// 遍历数组值并添加到表格中
$.each(response, function(index, value) {
$('#arrayTable tbody').append('<tr><td>' + value + '</td></tr>');
});
},
error: function(xhr, status, error) {
console.log(error); // 处理错误情况
}
});
});
</script>
</body>
</html>
get_array_values.php
的文件:<?php
$arrayValues = array('Value 1', 'Value 2', 'Value 3'); // 替换为实际的数组值
// 返回数组值的JSON格式数据
echo json_encode($arrayValues);
?>
以上代码中,通过Ajax发送GET请求到get_array_values.php
接口,获取到的数组值以JSON格式返回,并使用jQuery将其添加到表格中显示。
这种方法可以用于在表格中显示任意类型的数组值,无论是字符串、数字还是其他复杂的数据结构。
//点击追加触发
$(function(){
$("#button").click(function(){
var div_ = $("#sel").val();
var context = $("#context").val();
append(div_,context);
//$("#tab tr:not(:first)").remove();
//$("#tab tbody").empty();
$("#tab tbody").remove();
query();
});
});
//点击查询全部触发
$(function(){
$("#but").click(function(){
$("#tab tbody").remove();
//$("#tab tr:not(:first)").remove();
//$("#tab tbody").empty();
query();
});
});
//点击模糊查询触发
$(function(){
$("#query").click(function(){
var context = $("#context").val();
alert("您输入的内容为:"+context);
$("#tab tr:not(:first)").empty();
//$("table tbody").remove();
queryByContext();
});
});
//删除事件
function del(id){
var url = "testController/delModel";
$.ajax({
type: 'POST',
url: url,
data:{id: id},
dataType: 'json',
success: function(data){
alert("数据库删除成功");
$("#tab tr:not(:first)").empty();
query();
}});
};
//编辑事件
function upd(id){
var url = "";
$.ajax({
type: 'POST',
url: url,
data:{id: id},
dataType: 'json',
success: function(data){
alert("数据库编辑成功");
$("#tab tr:not(:first)").empty();
query();
}});
}
//添加方法
function append(div_,context){
$("#"+div_).append(" ");
$.get("testController/addModel",{div_id: div_, context: context }).done(function( data ) {
alert("添加到数据库成功");
});
};
//模糊查询方法
function queryByContext(){
var url = "testController/queryAllDataByContext";
$.ajax({
type: 'POST',
url: url,
data:{context:$("#context").val()},
dataType: 'json',
success: function(data){
alert("数据库查询成功");
console.log(data);
for(var i=0;i<data.length;i++){
var id = data[i].id;
var divId = data[i].divId;
var context = data[i].context;
var dtt = data[i].dtt;
//alert(id);
$("#tab thead").append(""+ div_ +" "+""+context+" ");
}
},
error:function(){
alert("数据库查询失败");
}
});
};
//查询全部方法
function query(){
var url = "testController/queryAllData";
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
success: function(data){
alert("查询成功");
con"+id+" "+""+divId+" "+""+context+" "+""+dtt+" "+"删除
领取专属 10元无门槛券
手把手带您无忧上云