【问题标题】:Save user data of html5 game using wordpress使用wordpress保存html5游戏的用户数据
【发布时间】:2012-05-07 08:50:36
【问题描述】:

我正在用 html5 编写游戏,并在网站的其余部分使用 wordpress。我希望用户能够保存他们的进度,但我不清楚架构的外观。

我只想对访问数据库的 php 页面进行 ajax 调用,但我觉得使用现有的 wordpress 数据库和 API 是正确的做法。不仅如此,使用 wordpress api 还能让我访问诸如 nonce 之类的东西。

也就是说,我是否要编写一个 wordpress 插件来做到这一点?如何从运行我的游戏的 javascript 正确执行保存请求?

【问题讨论】:

    标签: php wordpress html


    【解决方案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');
    

    【讨论】:

    【解决方案2】:

    如果您对比 wordpress API 允许的更通用的解决方案感兴趣(为了更全面地理解),下面是一个简单但完整的演示:

    这是 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.
    

    【讨论】:

    • 是否有理由不使用内置的 wordpress API?
    • @RodYan 我只是想鼓励更多的常识。我在我的 PHP 框架中使用 Codeigniter,它也有一些 JavaScript API。然而,随着时间的推移,我发现只写“香草”,也就是纯 PHP 和 JS 会更容易。除了提高一个人的一般知识之外,另一个主要原因是,与其他开发人员交谈变得更容易,其中大多数人不使用 Wordpress 或 Codeigniter。
    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    相关资源
    最近更新 更多