doudui6756 2016-10-29 15:23
浏览 370
已采纳

在javascript中处理PHP脚本

I've got a basic question to you. I'm creating several js scripts, like this:

<script>
$('#mapveto1').click(function() {
    $('#mapveto1').addClass('banned');
    $('#map1').text('cobblestone has been banned');
    <? $remaining = $remaining -1; ?>
    $('#banstatus').html('<span class="glyphicon glyphicon-repeat glyphicon-repeat-animate"></span> Maps are being banned <? echo $remaining; ?>');

});
</script>

In every script, the id of element is being changed. As you can see, there are some PHP variables in it.

The thing is, these php lines are being executed always, even when I don't run this script by clicking on the element. How can I make php scripts which will be executed ONLY when a js script is?

  • 写回答

1条回答 默认 最新

  • duanlan5320 2016-10-29 15:35
    关注

    Update: this example below to the way to pass variable in a sample way, but be ware about what $remaining variable output finally before passing it to Javascript using this way.

    another way to do the task with Ajax request witch recommended to POST & GET data.

    If you need to pass PHP variable to JavaScript global variable you can do like

    var js_variable = <?php echo $php_variable; ?>;//copy from php to js
    

    then use js_variable++ or js_variable-- with your click event or use js_variable wherever.

    So your Example will be

    <script>
    var remaining = <? echo $remaining; ?>
    $('#mapveto1').click(function() {
        $('#mapveto1').addClass('banned');
        $('#map1').text('cobblestone has been banned');
        remaining--;
       //or remaining -= 1;
       //or remaining = remaining -1;    
    $('#banstatus').html('<span class="glyphicon glyphicon-repeat glyphicon-repeat-animate"></span> Maps are being banned '+ remaining);
    
    });
    </script>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题