问题
So yeah this came to mind randomly when I was teaching someone how to redirect their page. I wasn't really sure what the main difference was... Is there a reason you would use one over the other? I guess if you are not coding in PHP, you would have to use the Javascript window.location
to redirect but would you ever use window.location
over PHP header
if you were developing in PHP? I feel they have very similar functions but perhaps I am missing something.
回答1:
The browser will process the header redirect right away, whereas the Javascript redirect will not be executed until the page has loaded (or at least enough of it to run the Javascript). Also, it will be the Javascript engine executing the redirect instead of the browser itself.
Doing it via the header will perform better. (slightly anyway...)
回答2:
PHP's server-side header can send other headers then only Location
. Javascripts client-side window.location
can be used to read, inspect, and alter (parts of the) current url, including hash. Really, they can do quite different stuff, and about their only overlap is both being able to redirect.
来源:https://stackoverflow.com/questions/13831618/what-is-the-difference-between-php-header-and-javascript-window-location