如何在页面加载时用JavaScript获取查询字符串并调用Controller方法
解决方案
完全可以通过JavaScript实现该需求,具体实现步骤如下:
第一步:调整跳转逻辑,完整传递参数
你当前的代码仅将id放到了路由路径中,若需要同时传递message参数,建议保留路由id规则的同时追加查询字符串,同时对参数做转义处理避免特殊字符出错,修改后代码如下:
function getDetails(id){ const message = "testing"; // id放在路由路径适配你现有路由规则,message放在查询字符串传递 window.location = `/FirmModels/Application/${id}?message=${encodeURIComponent(message)}`; // 如果需要把id也放在查询字符串可以用该写法: // window.location = `/FirmModels/Application?id=${id}&message=${encodeURIComponent(message)}`; }
第二步:Application.cshtml 页面加载时取参数并调用Controller接口
直接通过原生URLSearchParamsAPI即可解析查询参数,监听DOMContentLoaded事件就能在页面加载完成后自动执行逻辑,示例代码如下:
// 页面DOM加载完成后自动触发 document.addEventListener('DOMContentLoaded', function() { // 1、获取传递的参数 const url = new URL(window.location.href); // 若id放在路由路径中,取路径最后一段即可 const pathSegments = window.location.pathname.split('/').filter(segment => segment); const id = pathSegments[pathSegments.length - 1]; // 若id放在查询字符串中,用下面的方法取值: // const id = url.searchParams.get('id'); // 取查询字符串里的message参数 const message = url.searchParams.get('message'); // 2、调用Controller方法,示例为POST请求,可根据你的实际接口调整请求方式、参数 fetch('/FirmModels/GetDetail', { method: 'POST', headers: { 'Content-Type': 'application/json', // 如果是ASP.NET MVC项目需要防伪校验,补充下面这行即可 // 'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value }, body: JSON.stringify({ id: id, message: message }) }) .then(res => res.json()) .then(detailData => { // 拿到接口返回的详情数据后,自行渲染到页面对应位置即可 console.log('获取到的详情数据:', detailData); }) .catch(err => { console.error('请求出错:', err); }); });
旧浏览器兼容方案
如果需要兼容不支持URLSearchParams的低版本浏览器,可以使用自定义的解析方法:
function getQueryParam(name) { const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); const matchResult = window.location.search.substr(1).match(reg); return matchResult ? decodeURIComponent(matchResult[2]) : null; } // 调用示例:const message = getQueryParam('message');
内容的提问来源于stack exchange,提问作者user4221591
相关产品推荐
相关产品推荐

