Ajax成功回调中window.location.replace跳转出现undefined问题求助
问题分析与解决
你遇到的跳转时出现MYURL/undefined的问题,核心原因是JSON属性名大小写不匹配。
从你的调试信息来看,后端返回的JSON里属性名是小写的urlOne,但前端JS代码里却在判断大写的result.UrlOne——这会导致判断条件不成立,进而进入else分支尝试访问result.UrlTwo,而这个属性同样不存在,最终跳转路径变成了undefined。
解决方法
方法1:统一使用小写属性名(最简单)
修改后端控制器代码,将返回的属性名改为小写:
if (ModelState.IsValid && isNewUser == null) { //remove for clear code return Json(new { urlOne = Url.ActionLink("Index","Home")}); } TempData["ErrorMes"] = "You are allready register"; return Json(new { urlTwo = Url.ActionLink("_RegNews", "NewsLetter") });
然后修改前端JS代码,对应使用小写属性名:
success: function(result) { if (result.urlOne !== undefined) { window.location.replace(result.urlOne); } else { window.location.replace(result.urlTwo); } console.log(result); }
方法2:强制后端保留大写属性名
如果你需要保持大写的属性名,可以通过JsonPropertyName特性指定序列化后的名称(适用于ASP.NET Core,需引用System.Text.Json.Serialization命名空间):
using System.Text.Json.Serialization; // ... if (ModelState.IsValid && isNewUser == null) { return Json(new { [JsonPropertyName("UrlOne")] = Url.ActionLink("Index","Home") }); } TempData["ErrorMes"] = "You are allready register"; return Json(new { [JsonPropertyName("UrlTwo")] = Url.ActionLink("_RegNews", "NewsLetter") });
这种情况下,前端JS里的result.UrlOne和result.UrlTwo就能正确获取到对应的值。
额外检查
另外可以确认Url.ActionLink是否生成了完整的URL路径,如果生成的是相对路径,跳转时可能会基于当前页面URL拼接,但你的调试信息显示已经有正确的URL,所以这部分应该没问题。
内容的提问来源于stack exchange,提问作者Assaf Our
相关产品推荐
相关产品推荐

