简体   繁体   English

在PHP和JS中重定向而不刷新页面

[英]Redirecting in PHP and JS without refreshing the page

I am trying to make a web file server (a cloud). 我正在尝试制作Web文件服务器(云)。 I decided to put a basic form password auth on index.php . 我决定将基本形式的密码auth放在index.php When the user enters the password and clicks the button, JS sends that password to index.php and it decides if it correct. 当用户输入密码并单击按钮时,JS将该密码发送到index.php并决定是否正确。

If it is, then index.php redirects the user to files.php . 如果是这样,那么index.php会将用户重定向到files.php If not, then refreshes the page. 如果不是,则刷新页面。 I know that redirecting and refreshing is done through header(); 我知道重定向和刷新是通过header(); , but when I use this and watch the "Network" tab in my browser, it receives the files.php but doesn't load it (stays on index.php ). ,但是当我使用它并在浏览器中观看“网络”标签时,它会接收files.php但不会加载(停留在index.php )。 I am sure the reason is header sent after some text (well, it is header). 我确定原因是在某些文本之后发送了标头(嗯,它是标头)。

How do I redirect user's browser to some page after current page been sent? 发送当前页面后,如何将用户的浏览器重定向到某个页面? Should I ask JS to do it? 我应该问JS去做吗? Then how? 那怎么办 Here is my index.php: 这是我的index.php:

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php
  echo '
   <h1>Hello World</h1>
   <form>
    <input name="password" type="text"></input>
    <button onclick=authClick() class="test" type="button"></button>
   </form>
  ';
  print_r($_POST);
  if ($pass == "123123") {
   header("Location: files.php");
  }
 ?>
 <script src="scripts/main.js"></script>
 </body>
</html>

And here goes the JS: JS:

function authClick() {
 var editBox = document.querySelector('input');
 var xhr = new XMLHttpRequest();
 var body = 'password='+encodeURIComponent(editBox.value);
 xhr.open("POST","/index.php",true);
 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
 xhr.send(body);
}

var myHeading = document.querySelector('h1');
myHeading.textContent = 'nigga';
b = document.querySelector('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'submit';

You are using Ajax, and the point of Ajax is to make an HTTP request without loading a new page . 您正在使用Ajax,Ajax的目的是在不加载新页面的情况下发出HTTP请求。

Since you want to load a new page: Remove the JavaScript. 由于您想加载新页面:删除JavaScript。 Perform a regular form submission with a regular HTML submit button. 使用常规HTML提交按钮执行常规表单提交。

Using Js you can write it as follows 使用Js,您可以将其编写如下

window.open( response.data.url, '_blank');

If you want to open it directly in current tab 如果要直接在当前选项卡中打开它

window.open( response.data.url );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM