2012-09-19 321 views
0

我创建了一个双语言网站,其表单在提交时保存了一个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 } ?> 

语言切换正确,但只有当您点击提交按钮twi CE。

+1

所以你说,第一次点击'submit'按钮之一,表单是**没有**提交?如果是这样,您使用的是哪种浏览器,是否会在所有浏览器中发生? – billyonecan

+0

@deifwud当我点击提交按钮页面重新加载,然后当我再次点击页面重新加载,但这次语言实际上改变。所以要改变语言,我需要点击两次。我使用的是Chrome,但它发生在Safari和Firefox中。 – Rob

+1

好的 - 所以表单实际上是提交 - 你是否在**分配'$ language = $ _COOKIE ['region']'之前调用'set_region_cookie' **? – billyonecan

回答

3

原来,问题就出现了由于该饼干的工作方式的结果,发现了以下(重要)信息in this question

一个cookie的工作方式如下:

  1. 您提出请求
  2. 服务器SENDS Cookie返回客户端
  3. 页面加载 - Cookie对此页面上的PHP不可见加载
  4. 刷新
  5. 客户端发送的cookie头到服务器
  6. 服务器接收cookie头从而PHP可以读取它
  7. 的网页加载 - 曲奇这里是可见的。

我从来没有在第一次真正注意到了,但实际上存在的代码来处理,以使服务器接收到的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']); 
+0

我会尽快给予奖励! – Rob

0

请尝试使用选择字段。由于有两个提交按钮,浏览器可能会吓坏了。那么你可以做一些像document.getElementById('theSelectMenu').onchange = function(){ document.getElementById('theForm').submit(); }或更好的但它使用jQuery。

+0

我真的没有选择把它放在下拉菜单中,因为这是它的设计。 – Rob

相关问题