我有一个内存游戏代码,使用 javascript、php 和 css。
我想在 php 完成游戏时以某种方式注册事件,以便我可以将结果保存在数据库中。
换句话说,我想将 php 代码放在 <div id="player_won">
中</div>
并正确触发获胜事件。
CSS
#player_won{ display: none; }
javascript
$(document).ready(function(){ $(document).bind("game_won", gameWon); } function gameWon(){ $.getJSON(document.location.href, {won: 1}, notifiedServerWin); var $game_board = $("#game_board"); var $player_won = $("#player_won"); $game_board.hide(); $player_won.show(); $game_board = $player_won = null; };
最佳答案
您需要创建一个 ajax 调用,该调用从页面发送一些信息并告知下面的 php 文件玩家是赢了还是输了。之后,您可以在 foo.php 中处理播放器所需的逻辑,并将 Json 发送回 ajax 调用中的成功函数,并相应地更新您的页面。
索引
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>
关于javascript - 如何触发 javascript css 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40998139/