[英]Redirecting in PHP and JS without refreshing the page
我正在嘗試制作Web文件服務器(雲)。 我決定將基本形式的密碼auth放在index.php
。 當用戶輸入密碼並單擊按鈕時,JS將該密碼發送到index.php
並決定是否正確。
如果是這樣,那么index.php會將用戶重定向到files.php
。 如果不是,則刷新頁面。 我知道重定向和刷新是通過header();
,但是當我使用它並在瀏覽器中觀看“網絡”標簽時,它會接收files.php
但不會加載(停留在index.php
)。 我確定原因是在某些文本之后發送了標頭(嗯,它是標頭)。
發送當前頁面后,如何將用戶的瀏覽器重定向到某個頁面? 我應該問JS去做嗎? 那怎么辦 這是我的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>
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';
您正在使用Ajax,Ajax的目的是在不加載新頁面的情況下發出HTTP請求。
由於您想加載新頁面:刪除JavaScript。 使用常規HTML提交按鈕執行常規表單提交。
使用Js,您可以將其編寫如下
window.open( response.data.url, '_blank');
如果要直接在當前選項卡中打開它
window.open( response.data.url );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.