简体   繁体   English

重定向页面并调用javascript函数

[英]Redirect page and call javascript function

I need to redirect to another page onClick of submit and call a function making an ajax call. 我需要重定向到提交的onClick的另一页,并调用进行ajax调用的函数。 This is what I have : 这就是我所拥有的:

$('#submitButton').click(function() {

window.location.href = "otherPage";
displayData();
});

Also, Another way I tried is to set the form fields on otherPage by using 另外,我尝试的另一种方法是使用在otherPage上设置表单字段

var elem = window.document.getElementById(field);
elem.value = "new-value";

so that I could call the eventhandler of a submit button present on otherPage, but it doesn't work. 这样我就可以调用otherPage上存在的Submit按钮的事件处理程序,但是它不起作用。 Please let me know where I am wrong. 请让我知道我错在哪里。

I'm not sure if there is a neat way to achieve this, but you can add a hash in your url you redirect to, then just simply check if the hash exists, execute function and remove hash. 我不确定是否有一种简洁的方法来实现这一点,但是你可以在你重定向的url中添加一个哈希,然后只需检查哈希是否存在,执行函数和删除哈希。

Here are some handy URLs: 以下是一些方便的URL:

A hash (as Arko Elsenaar said) or a querystring parameter added to the target URL would allow you to detect what to do once there. 添加到目标URL的哈希(如Arko Elsenaar所述)或querystring参数将使您能够检测到在那里执行的操作。 The hash makes it a bit easier while the querystring is cleaner if you want to pass more information. 如果要传递更多信息,散列使得它更容易,而查询字符串更清晰。

For instance on the first page: window.location.href = "other/page.html#displayData"; 例如在第一页上: window.location.href = "other/page.html#displayData";

On the second page: 在第二页:

if (window.location.hash === '#displayData') {displayData();}

Another way could be to use the HTML5 Storage API, if and only if the 2 pages are on the same domain. 当且仅当两个页面位于同一域中时,另一种方式是使用HTML5 Storage API。

1st page would do, before the redirection: localStorage.displayData = true And the 2nd: if (localStorage.displayData) {displayData();} However in this case you'll need to clean up the localStorage.displayData value when used, otherwise it will stay there forever and your second page would always find it set to true. 在重定向之前 ,第一页会执行以下操作: localStorage.displayData = true和第二页: if (localStorage.displayData) {displayData();}但是,在这种情况下,使用时需要清理localStorage.displayData值,否则它将永远保留在那里,并且您的第二页将始终将其设置为true。 delete localStorage.displayData

All in all, the hash method seems best here. 总而言之,哈希方法在这里看起来最好。

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

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