Submit()重复执行&php仅接收默认值

时间:2018-12-24 05:46:48

标签: javascript php jquery post submit

我有一个使用POST方法的提交表单,没有提交按钮。

<form action="" method="post" id="submit_cookie_form">
   <input type="hidden" name="lang" value="" id="cookie_form">
</form>

我的目标:

  1. 将值传递给输入的隐藏值属性[* 1]
  2. 设置将值传递给value属性[* 2]时要执行/触发的代码
  3. 将值传递给值属性[* 3] =>问题
  4. 时提交表单
  5. 将Javascript值(“ en”或“ jp”)传递给php变量。 [* 4] =>问题

[* 3] => 当我对[* 3]使用submit()时,页面将被永久重新加载。似乎表格将永远提交。为什么会发生这种情况,我该如何修复代码?

[* 4] =>为什么php仅接收'en'值?虽然,<input type="hidden" name="lang" value="" id="cookie_form">的value属性根据用户在网页上的点击可以完美地接收'en''jp'。我该如何解决?

 let latestCookie;

    $(document).on('ready', function(){

       if (localStorage.getItem("language") === null || localStorage.getItem("language") === flag.en){
         document.cookie = "language=en";

       } else if (localStorage.getItem("language") === flag.jp){
         document.cookie = "language=jp";
       }

        latestCookie = getCookieValue('language');
        document.getElementById('cookie_form').value = latestCookie; //[*1]
        setLang(latestCookie); //[*2]
     })


      $('#cookie_form').change(function(){
          $('#submit_cookie_form').submit(); }); //[*3]

      function setLang(chosenLang){
          $('#cookie_form').val(chosenLang).trigger('change');
        }

   <?php 
         if(isset($_POST['lang'])){     
           $lang=$_POST['lang'];   //[*4]
           echo $lang;
         }
         else{
           echo $lang;
         }
   ?>

1 个答案:

答案 0 :(得分:0)

$('.dropdown-menu a img').on('click', function(){ 
    let flag = $(this).attr('src'); 
    $('#selected').attr('src', flag); 
    let key = $('#selected').attr('src'); 
    localStorage.setItem("language", key); 
    refreshPage(key); 
});
function refreshPage(key){
    window.location.href = '<php echo $_SERVER[\'PHP_SELF\']."?lang="; ?>'+key;
}

然后在PHP中,您可以使用GET方法作为查询字符串。

<?php 
     if(isset($_REQUEST['lang'])){     
       $lang=$_REQUEST['lang'];   //[*4]
       echo $lang;
     }
     else{
       echo $lang;
     }
?>