首页 > 解决方案 > 将代码从使用 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;
?>

标签: javascriptphpxhtml

解决方案


您正在使用$_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');
}

推荐阅读