[英]Javascript: Refresh current page after event change $_SESSION in a other page
I need help for a subtlety.我需要一些帮助。 I created a multilingual site without changing using the same php file, I just modify its content.
我创建了一个多语言站点,没有使用相同的 php 文件进行更改,我只是修改了它的内容。 For this I use sessions.
为此,我使用会话。 So I configured 2 buttons: FR and EN which change the language.
所以我配置了 2 个按钮:FR 和 EN,它们改变了语言。 I go through another php file.
我 go 通过另一个 php 文件。 With this code it works if I manually reload the page.
使用此代码,如果我手动重新加载页面,它就可以工作。 But if I use:
但如果我使用:
location.reload(true);
it doesn't work and i want to automatically reload the page without user intervention.它不起作用,我想在没有用户干预的情况下自动重新加载页面。 Does anyone have the solution?
有没有人有解决方案? Thanking you, Regards,
谢谢你,问候,
my code index.php:我的代码索引.php:
<?php
session_start();
if(isset($_SESSION['lang']) == false){
$_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link href="_style/style-master.css" rel="stylesheet" type="text/css">
<script type='text/javascript'>
function setSession(lang) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "change.php?lang=" + lang, true);
xmlhttp.send();
//here reload and refresh page after execute code in change.php
}
</script>
<title></title>
</head>
<?php
if($_SESSION['lang'] == "fr"){
echo "<body>";
echo "<p>Page française</p>";
echo "<a href=\"javascript:setSession('en')\"><input type='submit' value='EN'></a>";
echo "<a href=\"javascript:setSession('fr')\"><input type='submit' value='FR'></a>";
echo "</body>";
} else{
echo "<body>";
echo "<p>English page</p>";
echo "<a href=\"javascript:setSession('en')\"><input type='submit' value='EN'></a>";
echo "<a href=\"javascript:setSession('fr')\"><input type='submit' value='FR'></a>";
echo "</body>";
}
?>
</html>
change.php:更改.php:
<?php
session_start();
if(isset($_REQUEST['lang']))
{
$lang = $_REQUEST['lang'];
$_SESSION['lang'] = $lang;
}
?>
Your code reloads the index.php
immediately and doesn't even wait for the request (to change.php
) to be sent.您的代码会立即重新加载
index.php
并且甚至不等待发送请求(更改change.php
)。
You can handle the onreadystatechange event of XMLHttpRequest
, specifically you're looking for state 2, which is HEADERS_RECEIVED , or any later state.您可以处理
XMLHttpRequest
的onreadystatechange事件,特别是您正在寻找 state 2,即HEADERS_RECEIVED或任何更高版本的 Z9ED39E2EA931586B3A985A694EZEF5。
When the PHP script sends headers, it means it already finished executing (and set the session).当 PHP 脚本发送标头时,这意味着它已经完成执行(并设置会话)。 And you can safely reload the index page.
您可以安全地重新加载索引页面。
function setSession(lang) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 2) {
//here reload and refresh page after execute code in change.php
location.reload(true);
}
}
xmlhttp.open("GET", "change.php?lang=" + lang, true);
xmlhttp.send();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.