将代码从使用 GET 方法重写为使用 POST 方法

Rewriting code from using GET-method to using POST-method

提问人:OHiddema 提问时间:3/29/2019 最后编辑:OHiddema 更新时间:3/29/2019 访问量:41

问:

出于安全原因,我想将我的代码从使用 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;
?>
Javascript PHP XHTML

评论

0赞 Sanjit Bhardwaj 3/29/2019
这两个文件是否具有相同的名称 getcurrenthighscore.php ?
0赞 barbsan 3/29/2019
您的服务器是否准备好读取正文参数?
0赞 OHiddema 3/29/2019
@SanjitBhardwaj 是的,这两个函数都调用相同的 php 函数 (getcurrenthighscore.php)
1赞 barbsan 3/29/2019
查看 getcurrenthighscore.php 中的代码(它可能只读取 GET 参数)
2赞 Michel 3/29/2019
如果 POST 和 GET 都使用相同的函数,请确保在 php 中用作变量,而不是$_POST['q1']$_GET['q1']

答:

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');
}