提问人:OHiddema 提问时间:3/29/2019 最后编辑:OHiddema 更新时间:3/29/2019 访问量:41
将代码从使用 GET 方法重写为使用 POST 方法
Rewriting code from using GET-method to using POST-method
问:
出于安全原因,我想将我的代码从使用 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;
?>
答:
0赞
Michel
3/29/2019
#1
您正在使用 .POST 使用变量 .$_GET
$_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');
}
评论
$_POST['q1']
$_GET['q1']