JS:处理表格作为POST但检索为GET?

时间:2015-06-12 12:16:17

标签: javascript php ajax

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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);