JS:将表单作为 POST 处理,但作为 GET 检索


JS: Processing form as a POST but retrieving as a GET?

用PHP检索数据,我不能使用$_POST;而是$_GET。为什么?我发送的表单数据不正确吗?

我本以为request.open("POST"会将表单作为 POST 而不是 GET 处理?我如何将其作为邮寄方式发送?

var request = new XMLHttpRequest();
request.open("POST","email.php?text=" + textarea.value + "&email=" + email.value, true);
request.onload = function() {
    if (request.status >= 200 && request.status < 400) {
        var resp = request.responseText;
        console.log(resp);
    }
};
request.send();

因为您要在URL中添加数据。

将您的请求更改为:

request.open("POST","email.php", true);
request.setRequestHeader("Content-length", 2); // 2 here is the no. of params to send
....

request.send("text=" + textarea.value + "&email=" + email.value);

文档:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

原因是您正在发送 url 中的变量,这就是您进入 get 的原因。请参阅此示例帖子

var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny"; // all prams variable here
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);