【问题标题】:Submit buttons needing to be pressed twice to load page提交按钮需要按两次才能加载页面
【发布时间】:2012-09-11 13:16:25
【问题描述】:

我创建了一个双语言网站,其表单在提交时会保存一个 cookie,然后每个页面都会检查 cookie 以查看要加载的语言。

我遇到的问题是提交按钮需要按两次才能加载页面并切换语言。

这是我的表格:

<form action="<?php the_permalink(); ?>" name="region" method="post">
   <input type="submit" name="region" value="English" id="en-button" />
   <input type="submit" name="region" value="Cymraeg" id="cy-button" />
</form>

这是在我的functions.php文件中保存cookie:

function set_region_cookie()
{
    if(isset($_POST['region']))
    {
        // Set Cookie
        setcookie('region', $_POST['region'], time()+1209600);
        // Reload the current page so that the cookie is sent with the request
        header('Region: '.$_SERVER['REQUEST_URI']);
    }
}
add_action('init', 'set_region_cookie');

这就是我在每个内容区域周围加载不同内容的内容:

<?php $language = $_COOKIE["region"];
if ($language == "English") { ?>
    <?php echo the_field('english_content'); ?>
<?php } else { ?>
    <?php echo the_field('welsh_content'); ?>
<?php } ?>

语言会正确切换,但只有在您单击提交按钮两次时才能正确切换。

【问题讨论】:

  • 所以你是说第一次点击submit 按钮时,表单提交?如果是这样,您使用的是什么浏览器,所有浏览器都会出现这种情况吗?
  • @deifwud 当我单击提交按钮时,页面会重新加载,然后当我再次单击它时,页面会重新加载,但这次语言实际上发生了变化。因此,要更改语言,我需要单击它两次。我正在使用 Chrome,但它发生在 Safari 和 Firefox 中。
  • 好的 - 表单实际上正在提交 - 你是在调用set_region_cookie 之前分配$language = $_COOKIE['region']吗?
  • @deifwud 我不太确定! set_region_cookie 在我的functions.php 文件中,表单在我的header.php 文件中。
  • 我对 Wordpress 的设置了解不多,所以很遗憾,我无法为您提供太多帮助,请尝试找出在何处以及何时调用 set_region_cookie() 函数。听起来您正在尝试在设置 cookie 之前分配 $language = $_COOKIE['region'],这可以解释为什么它仅在第二次提交表单后才开始工作

标签: php html wordpress cookies


【解决方案1】:

尝试改用选择字段。浏览器可能只是因为有两个提交按钮而吓坏了。然后你可以做类似document.getElementById('theSelectMenu').onchange = function(){ document.getElementById('theForm').submit(); } 的事情,或者更好的是使用jQuery。

【讨论】:

  • 我真的没有选择将它放在下拉菜单中,因为它是这样设计的。
【解决方案2】:

原来问题出在cookie的工作方式上,发现了以下(重要)信息in this question

cookie 的工作方式如下:

  1. 您提出请求
  2. 服务器将 cookie 标头发送回客户端
  3. 页面加载 - Cookie 在此页面加载时对 PHP 不可见
  4. 刷新
  5. 客户端向服务器发送 cookie 标头
  6. 服务器收到 cookie 标头,因此 PHP 可以读取它
  7. 页面加载 - Cookie 在此处可见。

一开始我并没有真正注意到,但是问题中实际上有一行代码来处理刷新页面以便服务器接收cookie:-

// Reload the current page so that the cookie is sent with the request
header('Region: '.$_SERVER['REQUEST_URI']);

将其更改为:

// Reload the current page so that the cookie is sent with the request
header('Location: '.$_SERVER['REQUEST_URI']);

【讨论】:

  • 我会尽快奖励赏金!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多