无法在PHP中回显以Ajax发送的POST参数

时间:2018-10-27 06:00:48

标签: javascript php ajax

我正在将send方法内的两个参数发送到index.php。但是PHP返回错误“未定义索引”。 echo $ _POST ['fname'];

submit.addEventListener("click", function(e){
    e.preventDefault(); 
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "index.php", true);
    xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    xhr.onreadystatechange = function () {
      if(xhr.readyState == 4 && xhr.status == 200) {
        var result = xhr.responseText;
        console.log(result);
      }
    }
    xhr.send("fname=Henry&lname=Ford");
  });

1 个答案:

答案 0 :(得分:1)

为了通过Ajax发送表单数据,您必须指定请求的内容类型。如果您是'application/x-www-form-urlencoded

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

所以您的代码将是:

submit.addEventListener("click", function(e){
  e.preventDefault(); 
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "index.php", true);
  xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  xhr.onreadystatechange = function () {
    if(xhr.readyState == 4 && xhr.status == 200) {
      var result = xhr.responseText;
      console.log(result);
    }
  }
  xhr.send("fname=Henry&lname=Ford");
});