简单的AJAX POST后,$ _POST为空

时间:2016-07-31 12:28:13

标签: javascript php ajax post

我已经简化了我的代码以尝试隔离问题,但在javascript发送POST请求后,我似乎无法从php中的$ _POST变量中获取任何内容。看看这个:

<!DOCTYPE html>
<html>
<body>

<h2>AJAX Test</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      document.getElementById("demo").innerHTML = xhttp.responseText;
    }
  };
  xhttp.open("POST", "submit.php?name=david", true);
  xhttp.send();
}
</script>

</body>
</html>

这是submit.php

<?php
var_dump($_POST);
if(!empty($_POST))
{
    $name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);

    $output = json_encode(array('type'=>'message', 'text'=>$name.', thank you for your email!'));
    die("$output");
}
?>

当我按下按钮时,响应就是:

array(0) { }

_POST变量的空状态。

我在默认设置MAMP服务器上运行它,没有任何改变。怎么了?

2 个答案:

答案 0 :(得分:1)

您需要设置内容类型:

xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.open("POST", "submit.php?name=david", true);
xhttp.send();

顺便说一句,我不确定你的

?name=david

会工作......

答案 1 :(得分:1)

或者只是您可以在jquery中使用ajax method

$(document).ready(function() {
    $(document).on("submit", "#formID", function(e) {

        $.ajax({
            type: "POST",
            url: "WhereToPost.php",
            contentType: false,
            cache: false,
            processData: false,
            async: true,
            data: new FormData(this),
            success: function(data) {
                alert(data);
            },
            error: function() {
                alert("Error Handeling Here");
            }

        });
        e.preventDefault();
    });
});
相关问题