MVC (Model-View-Controller) 是一种设计模式,将应用程序分为三个主要部分:
Ajax (Asynchronous JavaScript and XML) 是一种无需重新加载整个页面即可与服务器交换数据并更新部分网页的技术。
首先创建一个返回JSON数据的控制器方法:
// 假设使用ASP.NET MVC
public class DataController : Controller
{
public ActionResult GetJsonData()
{
var data = new List<Person>
{
new Person { Id = 1, Name = "张三", Age = 25 },
new Person { Id = 2, Name = "李四", Age = 30 },
new Person { Id = 3, Name = "王五", Age = 28 }
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
创建一个视图页面,包含表格和Ajax调用:
@{
ViewBag.Title = "Ajax数据展示";
}
<h2>人员列表</h2>
<table id="dataTable" class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<!-- 数据将通过Ajax填充 -->
</tbody>
</table>
@section scripts {
<script>
$(document).ready(function() {
$.ajax({
url: '@Url.Action("GetJsonData", "Data")',
type: 'GET',
dataType: 'json',
success: function(data) {
var tableBody = $('#dataTable tbody');
tableBody.empty(); // 清空现有内容
$.each(data, function(index, item) {
var row = $('<tr>');
row.append($('<td>').text(item.Id));
row.append($('<td>').text(item.Name));
row.append($('<td>').text(item.Age));
tableBody.append(row);
});
},
error: function(xhr, status, error) {
console.error('Ajax请求失败: ' + status + ', ' + error);
}
});
});
</script>
}
如果需要更强大的表格功能(排序、分页、搜索等),可以使用DataTables插件:
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css">
@section scripts {
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var table = $('#dataTable').DataTable({
ajax: {
url: '@Url.Action("GetJsonData", "Data")',
dataSrc: ''
},
columns: [
{ data: 'Id' },
{ data: 'Name' },
{ data: 'Age' }
]
});
});
</script>
}
如果前端和后端不在同一域名下,可能会遇到跨域问题。解决方案:
确保后端返回的数据格式与前端期望的一致。可以在浏览器开发者工具中检查网络请求和响应。
对于大量数据:
始终实现错误处理回调,以便在请求失败时提供反馈:
error: function(xhr, status, error) {
alert('加载数据失败: ' + error);
console.error(xhr.responseText);
}
通过这种方式,你可以创建响应迅速、用户体验良好的Web应用程序,同时保持MVC架构的清晰分离。
没有搜到相关的文章