2012-05-06 18 views
0

我正在用html5編寫遊戲,並在網站的其他部分使用wordpress。我希望用戶能夠保存他們的進度,但我不清楚架構的外觀。使用wordpress保存html5遊戲的用戶數據

我只是做一個ajax調用訪問數據庫的php頁面,但我覺得使用現有的wordpress數據庫和API是正確的事情。不僅如此,而且使用wordpress api會讓我獲得像nonce這樣的東西。

這就是說,我寫一個wordpress插件來做到這一點?我如何正確執行來自運行我的遊戲的JavaScript的保存請求?

回答

1

在你的js文件,做你的Ajax請求是這樣的:

jQuery.post('path/to/wp-admin/admin-ajax.php', {action:'save_progress',other_parameter:'other_value'}, function(response) { 
    // let your user know if his progress is saved or not 
}); 

它添加到主題functions.php:

function save_progress() { 
    global $wpdb; 
    // do the saving job with received parameters here 
    die(); // this is necessary 
} 

add_action('wp_ajax_save_progress', 'save_progress'); 
+0

什麼是正確的方式去管理-ajax.php文件的相對路徑? – rysama

+0

您不必使用相對網址。只需使用它的網址「http://domain.com/wp-admin/admin-ajax.php」 –

1

如果您有興趣多了一個普及的解決方案下面是一個簡單但完整的演示:下面是HTML的代碼:

<input id="posted_data" ></input> 
<button id="saveBtn">Save</button> 

這裏的JS:

$(document.body).on('click', '#saveBtn', function(){   
    var posted_data=$('#posted_data').val(); 
    var url="/submit_page.php"; 
    $.ajax({url: url, data: {posted_data:posted_data }, type: "POST", 
     success: function(response){ 
       //do something with the `response` data 
     } //success 
    }); //ajax 
}); //.saveEditBtn 

這裏的submit_page.php:

$posted_data=$_POST['posted_data']; 
$posted_data; //do something with this variable, like insert it into a database 

echo "Success"; // this will be the `response` variable in the JS above. 
+0

有沒有理由不使用內置的WordPress的API? – rysama

+0

@RodYan我只是想鼓勵更多的常識。我爲我的PHP框架使用Codeigniter,它也有一些JavaScript API。然而,隨着時間的推移,我發現只寫「香草」,a.k.a.,純粹的PHP和JS更容易。除了提高一般人的知識外,另一個主要原因是與其他開發人員交談變得更容易,其他開發人員大多數不使用Wordpress或Codeigniter。 –