首页 > 解决方案 > 如何在数据库中存储 JavaScript 变量

问题描述

我想将值“totalscore”从我的 JavaScript 代码存储到我的数据库中。我尝试使用 ajax 调用但有些东西不起作用,我以前没有使用过 ajax。

在下面的 JavaScript 代码中,我将我找到的分数值显示给 html 元素。

JavaScript 代码:

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

单击提交按钮时,我想将 totalscore 的值保存在我的用户数据库中。所以我尝试了类似的东西:

   $("#sendscore").on("click",function(){

   gamescore= document.getElementById('score').innerHTML;
   $.ajax({
   type:'POST',
   url: 'score-processor.php',
   data:{
      gamescore: gamescore,
    }
   })
  });

php代码:

<?php
  session_start();
  $db = mysqli_connect('localhost', 'root', '', 'registration');
  if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password_1']);

  if (empty($username)) {
   array_push($errors, "Username is required");
  }
  if (empty($password)) {
   array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
    $_SESSION['username'] = $username;
     header('location: profile.php');
    }
    else {
    array_push($errors, "Wrong username/password combination");
   }
 }
}
   if(isset($_POST['gamescore'])){
   $fetch = "SELECT id FROM users WHERE username='$username'";
   $fetchid =mysqli_query($db, $fetch);
   while ($row=mysqli_fetch_array($fetchid)){
   $id = $row['id'];
   $gamescore= $_POST['gamescore'];
   $updatescore= "INSERT INTO users(id, score)VALUES('$id','$gamescore') ON DUPLICATE KEY UPDATE score='$gamescore'";
   mysqli_query($db, $updatescore);
   }
   }

在我的 html 中:

 <?php session_start();?>

 <body> 
 <p>Your score: <span id=score></p>
 <button id="sendscore" class="Go-on">Submit</button>

数据库表有列、id、username、email、password 和 score。

id、username、email 和 password 列的值是在登录/注册期间收集的。

游戏运行流畅并显示分数,但是当我单击提交按钮时,单击该按钮应将值添加到表中,但没有任何反应,日志中没有错误,并且值未添加到表中。

标签: javascripthtmlmysqlajax

解决方案


问题 1

gamescore= document.getElementById('score');

这是一个 HTML 元素,而不是它的值。

您需要.innerHTML像之前写的那样阅读


问题 2

gamescore: gamescore

jQuery.ajax 没有gamescore选项。所以这是没有意义的。

你需要通过data

data: {
    gamescore: gamescore
}

问题 3

contentType: false,

当您传递FormData对象以生成多部分请求(这对于上传文件很有用)时,这会阻止 jQuery 覆盖内容类型。

您没有这样做,因此contentType: false破坏正确 Content-Type 标头的正常分配。

删除那个


问题 4

processData: false

需要处理数据。您传递给的对象data需要编码到 HTML 请求中。

删除它。


问题 5

  $updatescore= "UPDATE users SET(username='$username', score='$gamescore') WHERE (id='$id')";

您未能定义$username$id


推荐阅读