Is it possible to call a javascript function after loading a page with window.location.assign? I have this code.
<script language="javascript" type="text/javascript">
function Loadspirit(){
window.location.assign("spirituality.php");
ReadEnglish();
}
</script>
I load the page then call ReadEnglish(), a function defined in spirituality.php. The function doesn't execute. What would be the way to make the function execute?
As soon as you assign a new window.location, the browser starts loading a new page in the current browser window. That stops execution of all javascript in this window and starts loading the new page. Only javascript in the new page will run from that point on. If you want a function after that new page is loaded, you will have to put that code in the new page. If want that function to run in the new page all the time, you can just set the code in that new page to always run that function when the page is loaded.
If you only want that new function to run in the new page when it's called from this particular context, then you need to pass some information to the new page and the code in the new page needs to look for that information to decide whether to run the ReadEnglish() function or not. The typical ways that you can pass information to the new page are
- Query parameters in the URL (items in the URL after the ? mark like "?run=English").
- Information set in a cookie
- Javascript variables in other windows/frames that are known to the new page and on the same origin.
Query parameters are often used if this is not a persistent setting, but rather an occasional execution of this option this particular time.
Cookies are often used if this is a more persistent setting because the cookie can persist until you tell it to go away.
I don't think you can do that. Your best bet would be to use the jquery library and then do something like:
$("body").load("spirituality.php", function() {
ReadEnglish();
});
No. The javascript past window.location.assign
will never get read. This function actually makes you leave the page and navigate to the argument.
If you want to stay on the current page and have access to some javascript on spirituality.php
you will need to load it via AJAX. If you actually are trying to navigate to 'spirituality.php' and load ReadEnglish();
, you need to call the function on spirituality.php
来源:https://stackoverflow.com/questions/6627983/calling-a-javascript-function-after-loading-a-page-with-window-location-assign