【问题标题】:JS: Processing form as a POST but retrieving as a GET?JS:将表单处理为 POST 但检索为 GET?
【发布时间】:2015-08-28 10:49:13
【问题描述】:

用PHP检索数据,我不能使用$_POST;但是$_GET。为什么?我是否错误地发送了我的表单数据?

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

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

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

    因为您要在 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

    【讨论】:

    • 有道理。所以我将参数添加到 request.send()?
    • 请同时使用 http.setRequestHeader("Content-length", params.length);
    • @FaizRasool 谢谢!已添加
    【解决方案2】:

    原因是您在 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);
    

    【讨论】:

    猜你喜欢
    • 2013-06-18
    • 2017-05-14
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    相关资源
    最近更新 更多