javascript - 将代码从使用 GET 方法重写为使用 POST 方法
问题描述
出于安全原因,我想将我的代码从使用 GET 更改为使用 POST。第一个函数 (getcurrenthighscoreGet) 完美运行(它返回一个字符串),但第二个函数 (getcurrenthighscorePost) 应该给出相同的结果,返回一个长度为零的空字符串。有谁知道第二个功能出了什么问题?
function getcurrenthighscoreGet(username) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("tdScore").innerHTML = parseInt(this.responseText);
}
};
xhttp.open("GET", "getcurrenthighscore.php?q1=" + username, true);
xhttp.send();
}
function getcurrenthighscorePost(username) {
var xhttp = new XMLHttpRequest();
var url = "getcurrenthighscore.php";
var params = "q1=" + username;
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("tdScore").innerHTML = parseInt(this.responseText);
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
调用的php函数:
<?php
require_once "connect.php";
$sql = "SELECT highscore FROM users WHERE username = ?";
$stmt = $con->prepare($sql);
if ($stmt->bind_param("s", $_GET['q1']) === false) {
die('binding parameters failed');
}
$stmt->execute() or die($con->error);
$stmt->bind_result($hs);
$stmt->fetch();
$stmt->close();
echo $hs;
?>
解决方案
您正在使用$_GET
. POST 使用变量$_POST
.
如果你想同时使用两者,你可以这样做:
$var = false;
if(isset($_GET['q1']))$var = $_GET['q1'];
else if(isset($_POST['q1']))$var = $_POST['q1'];
if($var===false) //trigger some error
然后使用$var
:
if ($stmt->bind_param("s", $var) === false) {
die('binding parameters failed');
}
推荐阅读
- ubuntu - 适用于 Linux 的 Windows 子系统在挂载时忽略元数据选项
- php - 如何使用安全规范发出 Soap 请求
- python-3.x - 尝试从 python 写入 cassandra 时 CQL 查询中的语法错误
- java - 引用变量 DataOutputStream 和 FileOutputStream
- ios - 无法将“字符”类型的值分配给“字符串”类型?
- android - 带有 RecyclerView 顶部和按钮视图的 ConstraintLayout 某些部分是不可见的。
- maven - 如何dockerize一个多模块springboot应用程序?
- typescript - React Native 如何在断点上下文中执行代码
- firebase - Firebase 部署不更新内容
- python - AttributeError:“用户”对象没有属性“is_active”烧瓶应用程序