![](/img/trans.png)
[英]How do I send a JavaScript variable into a PHP file via $.ajax()
[英]How do I get a JavaScript global variable and send it into a php file?
我正在使用Phaser游戏开发来开发游戏,我想将分数发送到mySQL数据库中,但是JS和PHP无法直接通信。 我正在使用AJAX,但遇到问题。 这是我的代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Star Runner</title>
<script>window.score=0;</script>
<script src="phaser.js"></script>
</head>
<body>
<script type="text/javascript">
// game goes here
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$(document).ready(function(){
$.ajax({
url: "inscore.php",
type: 'POST',
data: 'score='+score,
cache: false,
success: function(data) {
alert(data);}
});
});
</script>
<h1 style="color:white">Star Runner</h1
</body>
</html>
我的php文件'inscore.php'将是:
<?php
include 'login.php';
$score = $_GET['score'];
echo "<p>". $score. "</p>";
//SQL queries
?>
我不确定是否应该将此页面链接到php页面,因为我只想在游戏完成后立即将比分更新到我的数据库中。 有人可以帮帮我吗?
首先,您的代码中有一点错误。
您的代码:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> // code here will not run $(document).ready(function() { $.ajax({ // ... }); }); </script>
它应该是:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function() { $.ajax({ // ... }); }); </script>
这是为您提供的示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Star Runner</title> <script src="phaser.js"></script> </head> <body> <h1 style="color:white">Star Runner</h1> <div> Game stage ... </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> // game goes here var Game = { score: 0, run: function() { // your awesome code if (true) { this.gameOver(); } }, gameOver: function() { var _this = this; // send the request $.ajax({ url: "inscore.php", type: 'POST', data: 'score=' + this.score, cache: false, success: function(data) { // balabala console.log(_this); } }); } }; // Run the game Game.run(); </script> </body> </html>
最好使用OOP(面向对象编程),尤其是在游戏项目中。
由于要在ajax上发布数据,因此应该在PHP的$ _POST全局变量中获取数据
<?php
include 'login.php';
$score = $_POST['score'];
echo "<p>". $score. "</p>";
//SQL queries
?>
并尝试为此项目使用laravel或symfony这样的php框架,即使是苗条的简单框架也可以帮助您更好地完成工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.