无法通过Ajax将ASP.NET WebForms数据传递至客户端
解决Ajax加载资源失败的问题
针对你遇到的问题,可从以下几点调整:
1. 修正控制器返回类型,正确输出JSON响应
当前控制器返回字符串,未设置正确的Content-Type响应头,导致浏览器无法识别有效JSON。改用JsonResult返回,它会自动处理序列化逻辑和响应头配置:
[HttpGet] public JsonResult GetGraphData() { try { DataTable dt = new DataTable(); int[,] datar = new int[,] { { 1, 10 }, { 2, 15 }, { 3, 13 }, { 4, 17 } }; // 创建列 for (int i = 0; i < 2; i++) { dt.Columns.Add(); } for (int j = 0; j < 4; j++) { DataRow row = dt.NewRow(); for (int i = 0; i < 2; i++) { row[i] = datar[j, i]; } dt.Rows.Add(row); } // 直接返回DataTable,JsonResult会自动完成序列化 return Json(dt, JsonRequestBehavior.AllowGet); } catch (Exception ex) { // Web环境下建议用日志组件记录异常,比如log4net // 返回错误信息便于前端排查 return Json(new { error = ex.Message }, JsonRequestBehavior.AllowGet); } }
2. 优化Ajax请求配置
- 明确指定
dataType为json,告知jQuery预期接收JSON格式数据 - 使用
Url.Action生成正确请求地址,避免硬编码路径导致的路由错误:
$(document).ready(function () { $.ajax({ type: 'GET', // 借助Url.Action生成符合路由规则的地址 url: '@Url.Action("GetGraphData", "Home")', data: {}, dataType: 'json', success: function (result) { if (result.error) { alert("请求出错:" + result.error); console.error(result.error); } else { alert("Data is here"); console.log(result); } }, error: function (xhr, status, error) { alert("Data isnt here"); // 打印详细错误信息辅助排查 console.log("状态码:" + xhr.status); console.log("错误信息:" + error); } }); });
3. 额外排查点
- 打开浏览器控制台的Network标签,查看请求的状态码:404代表路径错误,500代表服务器端异常
- 确认项目已安装Newtonsoft.Json包(.NET Framework 4.5默认序列化可能依赖此包)
内容的提问来源于stack exchange,提问作者narutouzumaki 99
相关产品推荐
相关产品推荐

