简体   繁体   English

如何在重定向完成后执行一些jQuery或JavaScript代码

[英]How to execute some jQuery or JavaScript code after a redirect has completed

How can I execute jQuery/JS code as soon as a jQuery/JS redirect like... 我怎样才能像jQuery / JS重定向一样执行jQuery / JS代码...

$(location).attr('href','/target_path');

...or... ...要么...

window.location.href = "/target_path";

...has finished loading the new page? ...已经完成加载新页面?

Specifically, I need to pass an alert message and insert it into and display it (enclosed in some HTML) on the new page. 具体来说,我需要传递一条警告消息并将其插入并在新页面上显示(包含在某些HTML中)。

You can't. 你不能。 Once the redirect happens you are no longer on that page. 重定向发生后,您不再在该页面上。 You can't execute code on a page you are no longer on. 您无法在不再访问的页面上执行代码。 If you want the next page to do something then you need to pass, either by cookie or URL parameter, a flag that instructs it to do so. 如果您希望下一页执行某些操作,则需要通过cookie或URL参数传递一个指示它执行此操作的标志。

It is impossible to tell JavaScript to execute some code after a redirect. 在重定向之后,不可能告诉JavaScript执行某些代码。

However you have different options: 但是你有不同的选择:

  1. Pass a string in the redirect URL and then do something on "ready" 在重定向URL中传递一个字符串,然后在“就绪”上执行某些操作
  2. Store some information in a cookie and then do something on "ready" 将一些信息存储在cookie中然后“准备好”做一些事情
  3. Store some data using DOM storage (namely sessionStorage ) if you don't mind the smaller browser support 如果您不介意较小的浏览器支持,请使用DOM存储 (即sessionStorage )存储一些数据

You can't do that in the page that's redirecting. 您无法在重定向的页面中执行此操作。 You can read the referrer in the landing page ( document.referrer ), and then decide whether to display an alert based on that, though. 您可以在登录页面( document.referrer )中阅读引荐来源,然后决定是否显示基于此的警报。

var x = "It's some text";
var loc = '/target_path';

loc += '?message=' + encodeURI(x);

The JS file on the new page can then look at the query string to see if a message is there, and do the required action if it's detected. 然后,新页面上的JS文件可以查看查询字符串以查看是否存在消息,并在检测到时执行所需的操作。

You can use window.location.search on the new page to see what's there, although I'd recommend hunting for a deparam function in a library to turn the query string into a more usable object. 您可以在新页面上使用window.location.search来查看其中的内容,尽管我建议在库中搜索deparam函数以将查询字符串转换为更有用的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM