JS on change if checkbox is checked do function with php

问题: JS on change if checkbox is checked do this function with php, how I can do this, is this possible or no? $('.avflipswitch').on("change", function (e){ if(this....

问题:

JS on change if checkbox is checked do this function with php, how I can do this, is this possible or no?

 $('.avflipswitch').on("change", function (e){ 
        if(this.checked){
         functionOne(<?php $LinkOpen = '_blank';?>);
        }
        else{
         functionTwo(<?php $LinkOpen = '_self';?>);
        }
    });

cse

<gcse:searchresults-only linktarget="<?php echo $LinkOpen;?>"></gcse:searchresults-only>

回答1:

You can push the value to a cookie using JavaScript or jQuery and then let PHP retrieve the value from that cookie like this:

jQuery + PHP:

/* jQuery */

$('.avflipswitch').on("change", function (e){
  var blankTar = "_blank";
  var selfTar = "_self";

  if(this.checked){
    document.cookie = "target =" + blankTar;
    window.location.reload();
  }
  else{
    document.cookie = "target =" + selfTar;
    window.location.reload();
  }
});

/* PHP */

<gcse:searchresults-only linktarget="<?php echo $_COOKIE['target']; ?>"></gcse:searchresults-only>


JavaScript + PHP:

/* JavaScript */
var switch = document.querySelector(".avflipswitch")[0];
    
switch.addEventListener("change", function(){
  var blankTar = "_blank";
  var selfTar = "_self";
      
  if(this.checked){
    document.cookie = "target =" + blankTar;
    window.location.reload();
  }
  else{
    document.cookie = "target =" + selfTar;
    window.location.reload();
  }
}

/* PHP */

<gcse:searchresults-only linktarget="<?php echo $_COOKIE['target']; ?>"></gcse:searchresults-only>


回答2:

This is not possible: Your PHP code runs once to render the page, creating an HTML and Javascript string that is rendered in the user's browser. There's no way for a Javascript function in a user's browser to run PHP code on your server without making a request from the browser back to your server.


回答3:

What you are trying is not possible in php, but very easy with jquery:

$('.avflipswitch').on("change", function (e){ 
    if(this.checked){
     $('a').attr("target","_self")
    }
    else{
     $('a').attr("target","_blank")
    }
});
  • 发表于 2019-01-12 06:56
  • 阅读 ( 39 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除