[英]AJAX to send a JS variable to a PHP file (and then to DB)
我正在嘗試做的是 :
snake_game.php
。 他得到3分,我需要將當前分配給一個JavaScript變量的3值變成一個PHP變量,以便可以將其存儲到數據庫中一個名為high_scores
的表中。 問題):
資源 :
snake_game.php
是顯示游戲的容器所在的位置,以及高分div:
<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>
snake.js
可以找到所有JavaScript來創建游戲。 所有JavaScript都可以在上面的鏈接中查看。
我嘗試過的
從游戲的JS中,我相信分數保存在一個名為score- var score;
-知道了這一點,我嘗試了以下方法來嘗試獲得。 我試圖在線觀看一些教程,並提出了一些建議(位於snake_game.php
):
<script type="text/javascript">
function updateScore ()
{
var score = $('score').val();
$.post('snake_game.php', {postscore: score},
function ()
{
$('high_scores').html(data);
});
}
</script>
然后是PHP代碼:
<?php
$new_highscore= $_POST['score'];
echo json_encode($new_highscore);
?>
我相信以下是從JS獲取的數據嗎? 但是我不確定,我也不認為這是解決此問題的正確方法。
任何/所有幫助,將不勝感激:)
您無法在“就緒”功能之外訪問“得分”。 如果您想以上述方式實現事情,則必須添加全局參考來進行評分,盡管我會警告您,這通常是令人討厭的。
// 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;
........
弗雷迪,這是我能給您的最簡單的Ajax演示。 您需要研究並弄弄它,直到您了解發生了什么。 在理解下面的演示之后,您應該能夠在上面弄清楚如何做。 您將需要在我的示例文件中編輯<SCRIPT>文件路徑和AJAX URL到AJAXDEMO.PHP以匹配您的系統。
在一些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>
ajaxDemo.js文件:
// 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);
});
});
在服務器上的ajaxDemo.php文件中:
<?php
$result = [];
$result['scoreDoubled'] = $_POST['score'] * 2;
echo json_encode($result);
最終鼓勵:
在我看來,您可能會對前端代碼與后端代碼以及兩者之間的區別感到有些困惑。 只要記住,前端代碼在USER'S計算機上運行。 因此,當您訪問該游戲教程網站並加載Snake游戲時...該游戲正在您的計算機上運行。 后端代碼(PHP是一種后端語言)是在Web服務器上運行的代碼……通常意味着不在您的計算機上。 通過在帶有“ localhost”的計算機上運行Web服務器,您實際上是在將PC假裝為網站,從而可以快速測試和開發應用程序。 因此,任何對“ localhost”的Ajax調用都不必離開您的機器。 但是,在正常使用環境中,Ajax調用將通過Internet將請求發送到某些遠程服務器,例如www.MySite.com。 然后,MySite.com將處理使用PHP或其他某種語言發送給它的信息,然后發送回響應,該響應將由附加到ajax請求的“成功”功能進行處理。 然后,“成功”功能(通常稱為“回調”功能)會根據服務器發回的內容來更新HTML頁面,並生成一些結果。
如果我是你,我不會在香草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
});
3)我不太了解您對snake_game.php的解釋。 似乎您正在嘗試將其同時用作模板和端點。 如果您使用香草php做事,我強烈建議您不要這樣做,那么您需要另一個php文件來處理您的發帖請求。 例如:snake_high_scores.php。
//in snake_high_scores.php
//this is a really bad way to learn ajax requests. You should use a framework
$new_highscore= $_POST['score'];
//store this score in a db maybe you can pickup the user id from a session cookie
echo json_encode({data => {high_score => $some_highscore}});
除了上述答案外,我建議每當游戲加載時在頁面中提供高分(如果您不想向用戶顯示,則將其放置在隱藏的元素/輸入字段中),然后在游戲結束后將用戶得分與高分進行比較如果分數大於當前分數,則對php進行Ajax調用以存儲在數據庫中。
這適用於每個用戶(使用戶登錄后即可獲得用戶高分)或全局單個高分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.