如何在Ajax完成后重定向新页面并将响应传递至该页面?
几种实现Ajax响应结果传递到重定向页面的方法
你的需求很常见,Ajax请求完成后跳转到新页面并携带响应数据,这里有几个靠谱的实现方式,结合你的代码给你举例:
方法1:通过URL查询参数传递(适合小数据)
如果你的响应数据是短文本或者可以序列化的小数据,可以把它编码后拼到重定向的URL后面。注意要对特殊字符编码,避免URL解析错误:
function directtoedit(object) { $('#edit-field-tei-document-und-0-xml').focus(); $('#toolbar-back').show(); clickedTitle = object; $.ajax({ url: "tabs/get_old_contents.php", data: { seltitle: clickedTitle }, type: 'post', complete: function(response) { // 把响应内容转成URL安全的字符串,这里假设响应是文本 const encodedData = encodeURIComponent(response.responseText); // 拼接到重定向URL的查询参数里 location.href = `tabs/test.php?ajaxResponse=${encodedData}`; } }); }
然后在新页面test.php里,你可以通过URLSearchParams来读取:
// test.php的脚本里 const params = new URLSearchParams(window.location.search); const ajaxResponse = params.get('ajaxResponse'); // 解码后使用 console.log(decodeURIComponent(ajaxResponse));
这种方法的缺点是数据不能太大(URL长度有限制,不同浏览器略有不同),而且敏感数据不适合用这种方式,因为会暴露在URL里。
方法2:使用localStorage/sessionStorage存储(适合中等大小数据)
浏览器的本地存储可以跨页面传递数据,sessionStorage会在会话结束后自动清除,更适合这种临时传递的场景:
function directtoedit(object) { $('#edit-field-tei-document-und-0-xml').focus(); $('#toolbar-back').show(); clickedTitle = object; $.ajax({ url: "tabs/get_old_contents.php", data: { seltitle: clickedTitle }, type: 'post', complete: function(response) { // 把响应数据存到sessionStorage,注意如果是JSON要先转字符串 sessionStorage.setItem('ajaxResponse', response.responseText); // 重定向到新页面 location.href = "tabs/test.php"; } }); }
然后在test.php里读取并清理数据(避免下次页面加载还能读到):
// test.php的脚本里 const ajaxResponse = sessionStorage.getItem('ajaxResponse'); if (ajaxResponse) { // 使用响应数据 console.log(ajaxResponse); // 用完后删除,避免残留 sessionStorage.removeItem('ajaxResponse'); }
这种方法支持更大的数据量,也不会暴露在URL里,是比较推荐的方式。
方法3:使用Cookie传递(适合极小数据)
如果数据非常小(比如几个字符或者短ID),也可以用Cookie,但要注意Cookie的大小限制(约4KB):
function directtoedit(object) { $('#edit-field-tei-document-und-0-xml').focus(); $('#toolbar-back').show(); clickedTitle = object; $.ajax({ url: "tabs/get_old_contents.php", data: { seltitle: clickedTitle }, type: 'post', complete: function(response) { // 设置Cookie,有效期设为会话级别(关闭浏览器就失效) document.cookie = `ajaxResponse=${encodeURIComponent(response.responseText)}; path=/;`; location.href = "tabs/test.php"; } }); }
在test.php里读取Cookie:
// test.php的脚本里 function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return decodeURIComponent(parts.pop().split(';').shift()); } const ajaxResponse = getCookie('ajaxResponse'); if (ajaxResponse) { console.log(ajaxResponse); // 可选:删除Cookie document.cookie = "ajaxResponse=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"; }
这个方法适合极小数据,因为Cookie会在每次请求都发送到服务器,不适合大内容。
总结一下,优先推荐用sessionStorage,数据安全且容量足够;如果数据很小且需要服务器也能读取,可以用Cookie;URL参数只适合非敏感的短数据。
内容的提问来源于stack exchange,提问作者Ara
相关产品推荐
相关产品推荐

