在同一段代码中编写由 php、javascript 和 ajax 组成的代码是一种不好的做法吗?例如:
<?php
$randNum = rand(1,10)
if ($randNum <= 5) {
echo "Enemy got the jump on you! <script> enemyTurn() </script>";
}else {
echo "You got the jump! <script> playerTurn() </script>";
}
?>
enemyTurn()
、playerTurn()
是包含 jQuery 和 AJAX 的 JavaScript 函数。
最佳答案
是的,因为在浴缸里洗碗是一种不好的做法:你仍然可以这样做,但是当你需要的时候洗澡会很痛苦。
关注点应尽可能保持分离,例如:
PHP
<?php if ($randNum <= 5): ?>
<div data-function="enemyTurn">Enemy got the jump on you!<div>
<?php else: ?>
<div data-function="playerTurn">You got the jump!<div>
<?php endif; ?>
JS
$(function(){
var yourFunctions = {
enemyTurn : function(){ // some stuff },
playerTurn : function(){ // some stuff }
};
$('[data-function]').each(function(){
yourFunctions[$(this).data('function')].call(this);
})
});
这样你的js代码就与HTML解耦了。不过,我觉得你可以完成游戏客户端的所有逻辑,仅使用服务器进行登录/数据保存目的。
关于php - 在单段代码中混合 PHP、Javascript、Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16636125/