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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?