首页 > 解决方案 > 检查Javascript后重定向不起作用

问题描述

从下面的脚本中,我请求 index2.html 的状态。

我的http://test1.info/portal/#portal无法访问(Chrome)或显示(IE)。由于 URL 为“404”或未到达,因此不会将其重定向到index3.html

function website() {
  var req = new XMLHttpRequest();
  req.open('GET', 'http://mytest.info/index2.html', true);
  alert(req.status);
  req.send();

  if (req.status != "200"
    || "404") {
    window.location.href = "http://test1.info/portal/#portal";
  } else {
    alert("123");
    alert(req.status);
    window.location.href = "http://test.example.info/index3.html";
  }
}
<body onload="website()" >

我在哪里做错了?

标签: javascripthtml

解决方案


您的代码中有一些拼写错误:

  1. )你的body标签中有一个
  2. 你还没有关闭你的body标签
  3. if你使用的条件下or,它在 JS 中不存在(它是||),但在你的情况下,你的逻辑应该如下:req.status != "200" && req.status != "404"

解决这些问题后,您的代码应该可以工作:

function website() {
  var req = new XMLHttpRequest();
  req.open('GET', 'http://mytest.info/index2.html', true);
  alert(req.status);
  req.send();

  if (req.status != "200" && req.status != "404") {
    window.location.href = "http://test1.info/portal/#portal";
  } else {
    alert("123");
    alert(req.status);
    window.location.href = "http://test.example.info/index3.html";
  }
}
<body onload="website()"></body>


推荐阅读