1

在谷歌上四处寻找没有任何成功之后,我觉得在这里发帖可能是一个好主意,因为我已经使用这个网站来回答以前的问题。

无论如何,我目前正在使用 HTML5 画布游戏;

PHP, MYSQL, Html5, and JavaScript.

我有MYSQL数据库设置和一个PHP显示玩家高分和用户名的页面。我的问题是,一旦游戏结束,我将如何在画布内显示高分。

以及在游戏结束时保存高分。我在 W3SCHOOLS 网站上查看了有关 AJAX 的信息,但我仍然不确定在 JavaScript 文件中使用哪些代码。这些是我的 php/脚本代码。或至少是相关的:

// Here's the savescore.php file   
            <?php
                   include 'connect.php';

            $user_score = ($_POST['user_score']);
            $user_name = ($_POST['user_name']);

                if(mysql_query("INSERT INTO users VALUES('$user_name','$user_score')"))
                    echo "Score Successfully Saved";
                else
                    echo "Score Saving Failed";
            ?>
  // Here's some of the index.php file
            <link rel="stylesheet" href="css.css">
            </HEAD>
            <body>     
                <div id="menu">  
                    <a class="item" href="/index.php">Home</a>
              <?php 
            include 'connect.php';
            session_start();
                    if($_SESSION['signed_in'])  
                {  
                    echo 'Hello ' . $_SESSION['user_name'] . '. Not you? <a href="signout.php">Sign out</a>';  
                    include 'chat.php';
                }  
                else  
                {  
                    echo '<a href="signin.php">Sign in</a> or <a href="signup.php">create an account</a>.';  
                } 
                ?>
                </div>
            <BODY>
            <canvas id="canvasGAMEOVER" width="800" height="599"> </canvas> 
            <script src="game.js"> </script>

// here's whats inside inside game.js... well the part I want to be able to save score
            var score = 0;
            function drawGAMEOVER() {
                }

我使用谷歌并查看了 AJAX 教程,我找到了有关如何使用 AJAX 的教程和答案:

<form action="savescore.php">
  user_name: <input type="text" name="user_name"><br>
  user_score: <input type="text" name="user_score"><br>
  <input type="submit" value="Submit">
</form>

但我不确定是否可以获取他们登录时使用的“用户名”(显示在 index.php 页面上)以及 this.score(显示在 javascript 文件中)。谁能告诉我这是怎么可能的。 ..如果不是更好的方法呢?任何帮助/回复都非常感谢提前感谢。

4

3 回答 3

2

AJAX (short for Asynchronous Javascript And XML ) is a javascript object through which you can send requests to the webserver and get back its response asynchronously. Most of the modern browser support initializing AJAX requests via

var xmlHttp = new XMLHttpRequest();

Here is how you send a request

xmlHttp.open('GET' , 'file_in_server.php', false);

'GET' may be any other type of requests (like 'POST', 'PUT'...) and 'file_in_server.php' is the file where you send request, and falsemeans you are doing it synchronously.

After that line, you can write:

xmlHttp.send();

which sends the request you open()ed previously.

Now, the server sends back the response which you can capture by

var response = xmlHttp.responseText

Now response is anything echoed by your file_in_server.php

You can make use of asynchrous nature of AJAX. here's the sample code.

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState==4 && xmlHttp.status == 200){
        var capturedText = xmlHttp.responseText;
    }
};
xmlHttp.open('GET','file.php?a=1&b=2', true); //sends GET requests, with querystring.
xmlHttp.send();

The above code is asynchronous in nature. It does not block other script execution. The first line creates the XMLHttpRequest object On the second line, we are just creating an event listner that says that when the ready state of xmlHttp object is changes the function should be executed. . Now the execution goes to xmlHttp.open which initializes the process of requesting the server. This statement makes the XMLHttpRequest know that the request is asynchronous. after that the request is sent. As soon as the request is sent, the readystate of the object is changed, and the function above is called. That function checks for two condition, readystate of the object and returned status code and if the readystate is 4 (which means, ready), and the staus is 200 (which means OK), then it catches the response in the variable. Now you can use that variable to fulfill your motive.

if your file.php echoes the username currently logged in, then that will be catched in the variable capturedText

于 2013-07-19T18:33:46.747 回答
0

jQuery是一个 javascript 库,它将极大地简化您正在尝试做的事情。AJAX 请求基本上就像一个普通的 Web 请求,只是它是在浏览器中与 javascript 异步执行的。在 jQuery 中,您将执行以下操作:

$.ajax({
  url: "savescore.php",
  type: "post",
  data: {
    user_score: score,
    user_name: "fake_user"
  },
  success: function() {
    console.log("Finished uploading score");
  }
});
于 2013-07-19T18:14:12.553 回答
0

我不喜欢在没有 jQuery 的情况下做 ajax,所以我会给你一个例子。

链接到你想要的 jQuery... 最简单但不是我喜欢的方式:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>

创建一个可以从游戏中触发的函数...

function drawHighScore(){
    $.post('gethighscores.php', function(data){
    r = JSON.parse(data);

    $.each(r, function(k, v){
        context.fillText(k+":"+v, x, y);
        context.stroke();
    });
});

您的 gethighscores.php(简化版)...

query for name and score and then

while ($r = mysql_fetch_assoc($query)){ //***
$response[$r['name']] = $r['score'];
}

echo json_encode($response);

***关于查询/获取功能的 PDO 研究。

于 2013-07-19T18:20:05.410 回答