Javascript AJAX将JS变量发送到PHP文件(然后发送到DB)

Javascript AJAX将JS变量发送到PHP文件(然后发送到DB),javascript,php,jquery,ajax,html,Javascript,Php,Jquery,Ajax,Html,我正在尝试做的事情: 我的网站上有一款现成的HTML5游戏- 使用这个游戏,我想现在实现一个高分板,并显示在同一页上 例如,如果我以Conor身份登录,Conor将转到游戏所在的snake\u game.php。他得到了3分,我需要3的值,当前分配给一个JavaScript变量,变成一个PHP变量,这样我就可以将它存储到数据库中名为high_scores的表中 然后,一旦数据进入数据库,我就可以开始显示high score变量的结果,并在需要时更新数据 问题: <!DOCTYPE ht

我正在尝试做的事情

  • 我的网站上有一款现成的HTML5游戏-
  • 使用这个游戏,我想现在实现一个高分板,并显示在同一页上
  • 例如,如果我以Conor身份登录,Conor将转到游戏所在的
    snake\u game.php
    。他得到了3分,我需要3的值,当前分配给一个JavaScript变量,变成一个PHP变量,这样我就可以将它存储到数据库中名为
    high_scores
    的表中
  • 然后,一旦数据进入数据库,我就可以开始显示high score变量的结果,并在需要时更新数据
问题:

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Demo</title>
</head>

<body>
    <input type="text" name="score" id="scoreBox"><button id="sendScore">Send Score to Server Running PHP</button>
    <div id="result">The result from the server will be placed here...</div>
    <script src="/resources/js/jquery-1.12.3.js"></script>
    <script src="/resources/js/ajaxDemo.js"></script>
</body>
</html>
// This function uses AJAX to send the score from the HTML page running javascript to a web server running PHP.
function sendScoreToServer(theScore) {
    $.ajax({
        type: "POST",
        url: "http://localhost/ajaxDemo.php",
        data: { score: theScore },
        dataType: 'json',
        success: function(response){
            console.log(response);
            $('#result').html('The score returned by the server is: '+response.scoreDoubled);    
        }
    });   
}

// Once the HTML page finishes loading, this binds a 'onClick' event to the button that causes it to trigger the sendScoreToServer function.
$( document ).ready(function() {
    $('#sendScore').on('click', function() {
        var score = $('#scoreBox').val();
        sendScoreToServer(score);
    });
});
<?php
$result = [];
$result['scoreDoubled'] = $_POST['score'] * 2;
echo json_encode($result);
  • 我知道我必须使用AJAX来实现这一点,但我以前从未使用过AJAX
资源

snake\u game.php
是显示游戏的容器所在位置,以及高分分区:

<div id="wrapper">
     <div class="game_canvas">
         <canvas id="canvas" width="450" height="450"></canvas>  
         <script src="javascript/snake.js"></script>
     </div>
     <div class="high_scores" >
         High scores:             
     </div>  
</div>
然后是PHP代码:

<?php    
$new_highscore= $_POST['score'];    
echo json_encode($new_highscore);    
?>

我相信以下是从JS获取的数据?但我不确定,也不认为这是正确的方法


任何/所有帮助都将不胜感激:)

您不能在“就绪”功能之外访问“分数”。如果你想按照上面的思路来实现事情,你必须为score添加一个全局引用,尽管我要警告你,这通常是不受欢迎的

// Make a global reference to score 
var score; 

$(document).ready(function(){
    //Canvas stuff
    var canvas = $("#canvas")[0];
    var ctx = canvas.getContext("2d");
    var w = $("#canvas").width();
    var h = $("#canvas").height();

    //Lets save the cell width in a variable for easy control
    var cw = 10;
    var d;
    var food;
    //var score; THIS NOT NEEDED ANYMORE.
最好在ready()函数中使用Ajax调用添加函数,就像教程中的代码一样。游戏的工作方式是每次你碰到墙,游戏会通过调用“init”函数来重置自己。要想做你想做的事情,在分数重置为零之前,你需要将它发送到服务器。请参见下面的想法:

function init()
    {
        d = "right"; //default direction
        create_snake();
        create_food(); //Now we can see the food particle

        // Before resetting the score below, send the user score
        // to the server
        sendScoreToServer(score);

        //finally lets display the score
        score = 0;

        ........

编辑: Freddy,这是我能给你的最简单的Ajax演示。你需要研究这一点,直到你明白发生了什么。在您理解了下面的演示之后,您应该能够了解如何完成上面所述的任务。您需要在我的示例文件中编辑AJAXDEMO.PHP的文件路径和AJAX URL,以匹配您的系统

在某些HTML文件中:

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Demo</title>
</head>

<body>
    <input type="text" name="score" id="scoreBox"><button id="sendScore">Send Score to Server Running PHP</button>
    <div id="result">The result from the server will be placed here...</div>
    <script src="/resources/js/jquery-1.12.3.js"></script>
    <script src="/resources/js/ajaxDemo.js"></script>
</body>
</html>
// This function uses AJAX to send the score from the HTML page running javascript to a web server running PHP.
function sendScoreToServer(theScore) {
    $.ajax({
        type: "POST",
        url: "http://localhost/ajaxDemo.php",
        data: { score: theScore },
        dataType: 'json',
        success: function(response){
            console.log(response);
            $('#result').html('The score returned by the server is: '+response.scoreDoubled);    
        }
    });   
}

// Once the HTML page finishes loading, this binds a 'onClick' event to the button that causes it to trigger the sendScoreToServer function.
$( document ).ready(function() {
    $('#sendScore').on('click', function() {
        var score = $('#scoreBox').val();
        sendScoreToServer(score);
    });
});
<?php
$result = [];
$result['scoreDoubled'] = $_POST['score'] * 2;
echo json_encode($result);
在服务器上的ajaxDemo.php文件中:

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Demo</title>
</head>

<body>
    <input type="text" name="score" id="scoreBox"><button id="sendScore">Send Score to Server Running PHP</button>
    <div id="result">The result from the server will be placed here...</div>
    <script src="/resources/js/jquery-1.12.3.js"></script>
    <script src="/resources/js/ajaxDemo.js"></script>
</body>
</html>
// This function uses AJAX to send the score from the HTML page running javascript to a web server running PHP.
function sendScoreToServer(theScore) {
    $.ajax({
        type: "POST",
        url: "http://localhost/ajaxDemo.php",
        data: { score: theScore },
        dataType: 'json',
        success: function(response){
            console.log(response);
            $('#result').html('The score returned by the server is: '+response.scoreDoubled);    
        }
    });   
}

// Once the HTML page finishes loading, this binds a 'onClick' event to the button that causes it to trigger the sendScoreToServer function.
$( document ).ready(function() {
    $('#sendScore').on('click', function() {
        var score = $('#scoreBox').val();
        sendScoreToServer(score);
    });
});
<?php
$result = [];
$result['scoreDoubled'] = $_POST['score'] * 2;
echo json_encode($result);

如果我是你,我不会用普通的php来做这件事,但你当然可以

注意事项:

1) 您没有将响应数据传递到jQuery帖子中的回调方法中

2) 您没有使用jquery选择任何内容

        $.post('snake_game.php', {postscore: score}, 
        function (data) // <-- pass data in here; 
        {
            $('high_scores').html(data); //<!-- you aren't selecting anything here. 
            //if I were you I would make data a json
            //I would have something like
            $('.high_scores').append(data.high_score);
            //actually I have no idea why you even have this callback here

        });

除了上面的答案,我建议每当游戏加载使高分在页面中可用时(如果不想显示给用户,请放置在隐藏元素/输入字段中),然后在游戏结束后,将用户分数与高分进行比较(如果大于当前分数),然后对php进行Ajax调用以存储在DB中


这适用于每个用户(在用户登录后使用户高分可用)或全局单个高分。

$('score').val()
可能应该是
$('#score').val()。您需要在选择器中的ID之前放置
$('score')
查找类似
的元素,而
$('high\u scores')
应该是
$('high\u scores')
。您将
放在类名之前。您的
$。post
成功回调还应该有一个参数,
函数(数据)
。现在看起来您的
.html(数据)
正在使用未声明的变量。@Barmar-
$('#score').val()
正如您所提到的,ID选择器需要
#
。但我要澄清的是,
score
来自
snake.js
文件-
var score-我还需要它作为
$('#score').val()吗如果分数在Javascript变量中,则不需要从元素中获取。您好,谢谢您的回答。我理解你的方法,但是这可以用PHP实现吗?例如,您的方法是使用JavaScript向服务器发送数据,对吗?如果我误解了什么,请道歉