jQuery AJAX成功回调报错:Uncaught ReferenceError: $each is not defined
jQuery AJAX回调中$each未定义报错及数据遍历问题
问题描述
在jQuery AJAX的success回调函数中触发“Uncaught ReferenceError: $each is not defined”错误,目标是通过$.each遍历返回的结果数组并向表格追加数据行,但报错导致功能无法正常运行。
代码示例
HTML(FilteredAddressDetails.cshtml)
@model AmarisPrint.Models.FilteredAddressDetailsViewModel <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Filtered Address Details</title> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="~/Scripts/FilteredAddressDetails.js"></script> </head> <body> <div> <label for="selectedDate">Select Date</label> @Html.TextBox("selectedDate", Model.SelectedDate.HasValue ? Model.SelectedDate.Value.ToString("yyyy-MM-dd") : "", new { type = "date" }) <button id="getResultsBtn">Get Results</button> </div> <div id="filteredDataContainer" style="display: none;"> <table id="filteredDataTable"> <thead> <tr> <th>Student Name</th> <th>Parent Name</th> <th>Address</th> <th>Pin Code</th> <th>Mobile</th> <th>Email</th> <th>Timestamp</th> <th>Order No</th> </tr> </thead> <tbody> </tbody> </table> <p id="noDataMessage" style="display: none;">No data found for the selected date.</p> </div> </body> </html>
JavaScript(FilteredAddressDetails.js)
jQuery(document).ready(function () { $("#getResultsBtn").click(function () { var selectedDate = $("#selectedDate").val(); $.ajax({ type: "POST", url: "/Home/FilteredAddressDetails", data: { selectedDate: selectedDate }, success: function (result) { console.log(result); $.each(result, function (index, item) { var row = '<tr>' + '<td>' + item.OrderNo + '</td>' + '<td>' + item.StudentName + '</td>' + '<td>' + item.ParentName + '</td>' + '<td>' + item.Address + '</td>' + '<td>' + item.PinCode + '</td>' + '<td>' + item.Mobile + '</td>' + '<td>' + item.Email + '</td>' + '<td>' + item.TimeStamp + '</td>' + '</tr>'; $('#filteredDataTable tbody').append(row); }); $("#filteredDataContainer").show(); }, error: function (error) { console.log("Error:", error); } }); }); });
C#(FilteredAddressDetailsController.cs)
[HttpGet] public ActionResult FilteredAddressDetails() { var model = new FilteredAddressDetailsViewModel(); return View(model); } [HttpPost] public ActionResult FilteredAddressDetails(string selectedDate) { if (DateTime.TryParseExact(selectedDate, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDate)) { var filteredData = _db.AddressDetails .Where(ad => System.Data.Entity.DbFunctions.TruncateTime(ad.TimeStamp) == parsedDate.Date) .Join(_db.Orders, ad => ad.OrderId, o => o.Id, (ad, o) => new AddressDetailsViewModel { StudentName = ad.StudentName, ParentName = ad.ParentName, Address = ad.Address, PinCode = ad.PinCode, Mobile = ad.Mobile, Email = ad.Email, TimeStamp = ad.TimeStamp, OrderNo = o.OrderNo }) .ToList(); var viewModel = new FilteredAddressDetailsViewModel { SelectedDate = parsedDate, FilteredData = filteredData }; return View(viewModel); } return View(); }
Model类
public class FilteredAddressDetailsViewModel { public DateTime? SelectedDate { get; set; } public List<AddressDetailsViewModel> FilteredData { get; set; } } public class AddressDetailsViewModel { public string StudentName { get; set; } public string ParentName { get; set; } public string Address { get; set; } public string PinCode { get; set; } public string Mobile { get; set; } public string Email { get; set; } public DateTime TimeStamp { get; set; } public string OrderNo { get; set; } }
复现步骤
- 在输入框中选择日期
- 点击“Get Results”按钮
- 查看浏览器控制台中的报错
已尝试方案
- 将
$each替换为jQuery.each - 确认jQuery在脚本前已加载成功
- 检查jQuery冲突问题
预期行为
AJAX成功回调能通过$.each遍历结果数组,无报错地向表格追加数据行。
实际行为
浏览器控制台出现“Uncaught ReferenceError: $each is not defined”错误。
解决方案
核心问题分析
- 后端返回格式错误:当前后端Action返回的是完整HTML页面,而AJAX需要纯JSON数据。此时
result是HTML字符串,并非可遍历的数组,调用$.each会触发异常。 - 函数名拼写校验:确保使用
$.each(注意$与each间的点),而非$each(无点的未定义变量)。
具体修复步骤
修改后端Action返回JSON:
将POST方法的返回语句改为返回JSON数据:// 替换原return View(viewModel); return Json(filteredData, JsonRequestBehavior.AllowGet); // ASP.NET Core环境改为:return Json(filteredData);优化前端逻辑:
- 每次请求前清空表格,避免重复追加数据
- 处理无数据场景,显示提示信息
修改后的JS代码:
jQuery(document).ready(function () { $("#getResultsBtn").click(function () { var selectedDate = $("#selectedDate").val(); var $tbody = $('#filteredDataTable tbody'); var $noDataMsg = $('#noDataMessage'); // 清空表格内容 $tbody.empty(); $noDataMsg.hide(); $.ajax({ type: "POST", url: "/Home/FilteredAddressDetails", data: { selectedDate: selectedDate }, dataType: "json", // 指定接收JSON格式 success: function (result) { console.log(result); if (result.length === 0) { $noDataMsg.show(); } else { $.each(result, function (index, item) { var row = '<tr>' + '<td>' + item.StudentName + '</td>' + '<td>' + item.ParentName + '</td>' + '<td>' + item.Address + '</td>' + '<td>' + item.PinCode + '</td>' + '<td>' + item.Mobile + '</td>' + '<td>' + item.Email + '</td>' + '<td>' + item.TimeStamp + '</td>' + '<td>' + item.OrderNo + '</td>' + '</tr>'; $tbody.append(row); }); } $("#filteredDataContainer").show(); }, error: function (error) { console.log("Error:", error); } }); }); });验证jQuery引用:确保页面中jQuery的引用在自定义JS之前,且无版本冲突或加载失败情况。
内容的提问来源于stack exchange,提问作者LEVI A
相关产品推荐
相关产品推荐

