简体   繁体   English

使用wordpress保存html5游戏的用户数据

[英]Save user data of html5 game using wordpress

I'm writing a game in html5 and using wordpress for the rest of the site. 我正在用html5编写游戏,并在网站的其余部分使用wordpress。 I want users to be able to save their progress, but I'm not clear on how the architecture looks. 我希望用户能够保存他们的进度,但我不清楚架构的外观。

I would just do an ajax call to a php page that access the database, but I feel like using the existing wordpress database and API is the correct thing to do. 我只是对访问数据库的php页面进行ajax调用,但我觉得使用现有的wordpress数据库和API是正确的做法。 Not only that, but using the wordpress api will give me access to things like nonce. 不仅如此,使用wordpress api还可以访问nonce之类的东西。

That said, do I write a wordpress plugin to do this? 那就是说,我写一个wordpress插件来做这个吗? How do I properly execute the save request from the javascript that runs my game? 如何从运行我的游戏的javascript中正确执行保存请求?

In your js file, do your ajax request like this: 在你的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
});

add this to your theme's functions.php: 将此添加到主题的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');

If you're interested in a more generalizable solution than what the wordpress API allows (for more overall understanding), below is a simple, but complete demo: 如果您对wordpress API允许的更通用的解决方案感兴趣(为了更全面的理解),下面是一个简单但完整的演示:

Here's the HTML: 这是HTML:

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

Here's the JS: 这是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

Here's the submit_page.php: 这是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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM