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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题