2

我在我的 html 页面末尾加载了一个带有函数 loginsucces() 的 javascript,它应该在成功登录重定向到页面后执行。它在默认浏览器模式(chrome)下完美运行,但是当我以隐身模式加载页面时,它会在第一次加载页面时执行该功能。由于这种行为,我得到了语法错误,因为 php 变量尚未初始化。我知道我可以以某种方式解决这个问题,但我很想知道为什么 js 函数在首次页面加载时以隐身模式执行,我该如何避免这种情况?

<script>
function loginsuccess(){
  if(!<?php echo isAuth() ?>){ return; }

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200){
          var json = JSON.parse(xhr.responseText);
          ...    
      }
  }
  xhr.open("GET","http://myurl.com/api/users/"+<?php echo currentUserId()?>,true);
  xhr.send();
}
</script>
4

1 回答 1

1

你也许应该这样做。

<script>
<?php if (isAuth()): ?>
function loginsuccess(){
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200){
          var json = JSON.parse(xhr.responseText);
          ...    
      }
  }
  xhr.open("GET","http://myurl.com/api/users/"+<?php echo currentUserId()?>,true);
  xhr.send();
}
<?php endif ?>
</script>

或者,为了让事情分开并允许您稍后将代码移出,而不是内联,是预先在全局变量中定义状态。

这可以放在head文档中。

<?php if (isAuth()): ?>
<script>
var user = {
  loggedIn: true,
  userId: <?php echo currentUserId()?>
};
</script>
<?php endif ?>

现在您的 js 中没有 PHP 变量,如果您愿意,可以将其移出到 .js 文件中。

<script>
function loginsuccess() {
  if (typeof user === "undefined" || user.loggedIn !== true) {
    return
  }
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
      if (xhr.readyState == 4 && xhr.status == 200){
          var json = JSON.parse(xhr.responseText);
          ...    
      }
  }
  xhr.open("GET","http://myurl.com/api/users/"+user.userId,true);
  xhr.send();
}
</script>
于 2018-03-10T07:54:24.970 回答