Javascript 无法在PHP内回显ajax中发送的POST参数

Javascript 无法在PHP内回显ajax中发送的POST参数,javascript,php,ajax,Javascript,Php,Ajax,我将send方法中的两个参数发送到index.php。但是PHP返回一个错误“未定义索引”。echo$_POST['fname'] 为了通过Ajax发送表单数据,必须指定请求的内容类型。在您的情况下,它将是'application/x-www-form-urlencoded: xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 因此,您的代码将是: submit.addEventListener("

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


为了通过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");
});
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");
});