2016-12-06 68 views
1

我有一個記憶遊戲代碼,使用javascript,php和css。我該如何觸發javascript css動作?

我想通過PHP完成遊戲時以某種方式註冊事件,以便我可以將結果保存在數據庫中。

換句話說,我想將php代碼放在<div id="player_won"></div>之內,並正確地觸發該獲勝事件。

  1. CSS

    #player_won{ 
    display: none; 
    } 
    
  2. 的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; 
    }; 
    
+1

你應該儘量縮小您的問題,只發布了相關的代碼。 – jeroen

+1

你可以在你的遊戲中獲得ajax函數,然後將結果放在你想要的元素中 – Pete

+0

我已經縮小了代碼範圍。你能舉一個例子說明如何激發ajax函數,將結果放入元素中? – chejnik

回答

1

你要創建一個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 

     } 
    } 
?> 
+0

它幫了我很多。有一個小錯字 - output.answer,編輯太小,無法糾正。謝謝 – chejnik

+0

我在這裏寫了大部分來自內存中的代碼,所以出現了一點問題,不是問題:-) –

相關問題