javascript - 如何在数据库中存储 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 列的值是在登录/注册期间收集的。
游戏运行流畅并显示分数,但是当我单击提交按钮时,单击该按钮应将值添加到表中,但没有任何反应,日志中没有错误,并且值未添加到表中。
解决方案
问题 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
。
推荐阅读
- jquery - 如何查看页面源 VS 检查?
- css - reactjs创建部分可滚动的表格
- javascript - 如何使用用户输入的 int 显示枚举值?
- java - GWT ui.xml 转换
- python-3.x - 使用一系列指标构建 Astropy 表
- node.js - 在 Node.js(快速框架)中处理文本的有效方法是什么?
- python - 'MediaDefiningClass' 对象不可迭代 - django-import-export
- r - 获取目录中的文件名列表
- mongoose - 带有猫鼬模式数据的嵌入或引用文档?
- selenium - 启动范围报告挂钩管理器以使用 Specflow