【问题标题】:Can't pass a parameter to $_POST using the XMLHttpRequest无法使用 XMLHttpRequest 将参数传递给 $_POST
【发布时间】:2020-09-17 14:47:49
【问题描述】:

我正在练习 PHP 和 XMLHttpRequest 对象的使用。我正在尝试创建一个函数来检查用户名是否已被使用。

这是我的 javascript 函数:

function checkUser(username) {
if (username.length < 8) return 2;

request = new XMLHttpRequest();

request.open("POST", "checkUser.php?t=" + Math.random(), true);
request.setRequestHeader('Content-type', 'application/x-www-urlencoded');
params = 'nameToBeChecked=' + username; 

request.onreadystatechange = function() {
    if(request.readyState == 4 && request.status == 200) {
        if(request.responseText == "true") {
            return 1;
        }
        else if (request.responseText == "false") {
            return 0;
        }
        else console.log("ERROR: " + request.responseText);
    }
}
request.send(params);
}

这是我的 PHP 文件:

require 'userActions.php';

if(isset($_POST['nameToBeChecked'])) {
    if(fetch_userid($_POST['nameToBeChecked']) == null) echo "true";
    else echo "false";
}
echo !isset($_POST['nameToBeChecked']) ? "Field doesn't exist" : "Field exists" ;

我的 PHP 文件的最后一行用于调试目的。我发现当我向 PHP 文件发送 POST 请求时,未在 PHP 文件中创建字段 nameToBeChecked。我在网上找不到问题所在。有人可以帮忙吗?

【问题讨论】:

    标签: javascript php xmlhttprequest


    【解决方案1】:

    更改此行后重试:

    /* request.setRequestHeader('Content-type', 'application/x-www-urlencoded'); */
    request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    

    定义如下:application/x-www-form-urlencodedfrom https://developer.mozilla.org/

    【讨论】:

    • 很高兴它成功了!如果这对您有帮助,请接受答案:)
    • 我做到了,我也想投票,不幸的是,我的帐户仍然太新:(
    猜你喜欢
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2015-11-11
    • 2020-05-15
    • 2015-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多