为什么我们不在Javascript中重定向后退出/死掉脚本?

use*_*399 5 javascript php redirect exit

我们需要exit;在php中重定向之后做,因为exit;不会阻止其余的代码运行.但是为什么我们不在javascript中做那样的事情.我想做点什么

if(window.location.replace("http://something.com")){
  return;
}
Run Code Online (Sandbox Code Playgroud)

要么

window.location.replace("http://something.com");
throw "stop the execution.";
Run Code Online (Sandbox Code Playgroud)

我需要那样做吗?如果不是为什么?

mit*_*esh 5

为什么我们需要exit();在php中重定向后做?

当你做

header( "Location: ./somepage.php" );
Run Code Online (Sandbox Code Playgroud)

因为php manual on header saysheader() 用于发送原始 HTTP 标头。所以它不会阻止脚本进一步执行。它将与重定向相关的响应头发送回浏览器并继续执行下面的代码。所以exit()会阻止这样做。

我们需要return;在 window.location 调用之后吗?

JS 代码告诉浏览器导航到另一个 url。所以当导航完成时。浏览器导航到新页面,下面的代码window.location不会像上面解释的 php 行为那样被执行。所以我们不需要它。