简体   繁体   English

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

[英]Rewriting code from using GET-method to using POST-method

For security reasons I want to change my code from using GET to using POST. 出于安全考虑,我想将我的代码从使用GET更改为使用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. 第一个函数(getcurrenthighscoreGet)完美地工作(它返回一个字符串),但第二个函数(getcurrenthighscorePost)应该给出相同的结果,返回一个零长度的空字符串。 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函数:

<?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;
?>

You are using $_GET . 您正在使用$_GET POST uses the variable $_POST . POST使用变量$_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 : 然后使用$var

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM