javascript - 如何使用 ajax 在 Javascript 中发送 gamescore 元素

标签 javascript php ajax

我开发了一个带有图像的内存游戏。游戏运行良好。我的问题是分数。游戏完成后,分数将显示在屏幕上,并带有“提交”按钮。因此,当我单击按钮时,分数应添加到数据库中。我尝试使用 ajax、php 和 Javascript。

提交按钮的 php 代码:

游戏.php:

<?php session_start();
 ?>

 <body> 
   <div align='center'>
        <button class="play-again" onclick="reset()>Play Again</button>
        <button id="sendscore" class="Go-on"><a href="gallery.php">Submit</a></button></div></p>
    </div>

计算得分的游戏逻辑:

gameply.php:

 <? php ?>

 <script type="text/javascript">

 var gamescore;
 var totalscore;

 if(matches =='8'){
   var totalscore = calcScore();
   document.getElementById("score").innerHTML= totalscore;
 }

 function calcScore(){
var tilesbonus = (matches) * 20; // 20 points for each successful tile
var timebonus = (finaltime) * 2;  // 8 points for each second
var triesbonus = (30 - moves) * 5;  // (deduct) 10 points for each try
if (tilesbonus <0) { tilesbonus = 0; }
if (timebonus <0) { timebonus = 0; }
if (triesbonus <0) { triesbonus = 0; }
totalscore = tilesbonus + timebonus + triesbonus;
return totalscore;
}


$("#sendscore").on("click",function(){
gamescore= document.getElementById("score").innerHTML;
$ajax({
  type:'POST',
  url: 'server.php',
  data:{
      'gamescore': gamescore,
  },
  success: function(data)
                {
                alert('score is submitted');      }
   }) 
  });

  </script>

获取ajax调用并将分数存储到表中的代码:

服务器.php:

  <?php
   session_start();
   if(isset($_POST['gamescore'])){
   $username=$_SESSION['username'];
   $fetch = "SELECT * FROM users WHERE username='$username'";
   $fetchid =mysqli_query($db, $fetch);
   while ($row=mysqli_fetch_array($fetchid)){
   $id = $row['id'];
   $username=$row['username'];
   $gamescore= $_POST['gamescore'];
   $updatescore= "UPDATE users SET score='$gamescore' WHERE id = '$id'";
   mysqli_query($db, $updatescore);

   $finalscore="UPDATE users SET sum_score = (sum_score + $gamescore) WHERE id='$id'";
   mysqli_query($db,$finalscore);
   }
   }
   ?>

我遇到的问题是当我单击提交按钮时,分数未添加到数据库中。我得到的错误是 $("#sendscore").on("click",function(){

行上 undefined symbol '$'

最佳答案

您尚未将 Jquery 包含到您的文件中。

请添加

 `<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>`

此行位于 </html> 之前标签。

关于javascript - 如何使用 ajax 在 Javascript 中发送 gamescore 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132772/

相关文章:

php include css vs html link css(对服务器和用户体验的影响)

php - 如果我的表单使用的是 ajax 提交方法(无需重新加载),我该如何阻止垃圾邮件?

javascript - AJAX GET 调用将在第一次调用时起作用,但在其他点击后不起作用

javascript - Zend Framework 1.12,ContextSwitch或AjaxContext不会禁用布局和其他问题

javascript - 如何从Jquery中的字符串中提取子字符串

javascript - 在 JavaScript 闭包中重新定义局部变量

javascript - 使对象不可调用

javascript - node.js 找不到模块 './lib/compat'

php - MySQL插入数据后需要转义

ajax - 我如何使用 <p :fileUpload> with mode simple and ajax ="true"?