dopgl80062 2019-03-29 07:09
浏览 100

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

For security reasons I want to change my code from using GET to using POST. The first function (getcurrenthighscoreGet) works perfectly (it returns a string), but the second function (getcurrenthighscorePost) which should give the same result, returns an empty string with zero length. Does anyone have a clue what is going wrong in the second function?

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

The php function that is called:

<?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;
?>
</div>
  • 写回答

1条回答 默认 最新

  • douba2705 2019-03-29 07:38
    关注

    You are using $_GET. POST uses the variable $_POST.

    If you want to use both, you can do:

    $var = false;
    
    if(isset($_GET['q1']))$var = $_GET['q1'];
    else if(isset($_POST['q1']))$var = $_POST['q1'];
    
    if($var===false) //trigger some error
    

    And then use $var:

    if ($stmt->bind_param("s", $var) === false) {
      die('binding parameters failed');
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)