如何通过Ajax将MVC生成的脚本字符串传递给JavaScript执行
解决MVC后端返回脚本字符串在前端AJAX中执行的问题
我来帮你搞定这个问题——你现在遇到的核心问题是:AJAX请求拿到后端输出的脚本字符串后,浏览器不会自动解析执行它,必须手动处理才行。下面给你两种可行的方案,其中第二种更推荐,因为更符合前后端交互的规范:
方案一:直接执行后端返回的脚本字符串
这种方法最直接,就是在AJAX的success回调里,把后端返回的脚本字符串手动执行。你可以用eval()或者动态创建<script>标签来实现:
修改你的前端AJAX代码:
function GiveTicket(applyId) { var voteId = $('input[name="Id"]').val(); var captcha = $('input[name="Captcha"]').val(); $.ajax({ url: '@Url.Action("GiveTicket", "Vote")', data: { applyId: applyId, voteId: voteId, cptcha: captcha }, type: 'Get', success: function (data) { // 方法1:用eval执行脚本(注意:仅当你完全信任后端输出的内容时使用,避免XSS风险) eval(data); // 方法2:动态创建script标签插入页面(相对更安全一点) // const scriptTag = document.createElement('script'); // scriptTag.textContent = data; // document.body.appendChild(scriptTag); } }); }
⚠️ 注意:这种方式存在XSS安全风险,如果后端输出的脚本被恶意篡改,可能会导致安全问题,所以只适合内部信任环境使用。
方案二:改用JSON格式返回指令(推荐)
更规范的做法是后端不直接输出脚本,而是返回JSON格式的指令数据,前端根据指令类型(比如Alert、Confirm)来执行对应的操作。这种方式更安全、易维护,也符合前后端分离的思路。
修改后端代码
把原来的Response.Write和return null改成返回JsonResult:
public ActionResult GiveTicket(Guid voteId, Guid applyId, string cptcha) { var canVoteWay = _voteService.GetVoteWay(voteId); string message = string.Empty; string loginPath = $"{ConfigurationManager.AppSettings["DomainName"]}/Account/Login?returnUrl={Request.UrlReferrer}"; if (User.Identity.IsAuthenticated && WebLogic.HasValue(canVoteWay, (int)CurrentUser.LoginType)) { if (string.IsNullOrEmpty(cptcha) || cptcha != Session["VerificationCode"]?.ToString()) { return Json(new { Type = "Alert", Message = "圖形驗證碼驗證錯誤,請重新輸入!!" }, JsonRequestBehavior.AllowGet); // 允许GET请求返回JSON } // 执行投票逻辑 // var result = _voteService.GiveTicket(voteId, applyId, CurrentUser.Id, CurrentUser.LoginType); return Json(new { Type = "Alert", Message = "投票成功" }, JsonRequestBehavior.AllowGet); } message = _voteService.VoteWayString(canVoteWay, "請先登入,才能參與投票!! 投票允許登入的方式:"); return Json(new { Type = "Confirm", Message = message, RedirectUrl = loginPath }, JsonRequestBehavior.AllowGet); }
修改前端AJAX代码
根据后端返回的JSON指令,触发对应的弹窗和跳转逻辑:
function GiveTicket(applyId) { var voteId = $('input[name="Id"]').val(); var captcha = $('input[name="Captcha"]').val(); $.ajax({ url: '@Url.Action("GiveTicket", "Vote")', data: { applyId: applyId, voteId: voteId, cptcha: captcha }, type: 'Get', dataType: 'json', // 指定接收JSON格式数据 success: function (response) { switch(response.Type) { case "Alert": bootbox.alert(response.Message); break; case "Confirm": bootbox.confirm(response.Message, function(isConfirmed) { if(isConfirmed) { window.location.href = response.RedirectUrl; } }); break; } }, error: function() { bootbox.alert("操作失败,请稍后重试"); } }); }
这种方案的优势很明显:前后端职责清晰,避免了脚本注入风险,后续扩展新的提示类型也非常方便。
内容的提问来源于stack exchange,提问作者Leon Huang
相关产品推荐
相关产品推荐

