【问题标题】:Not able to echo POST paramenters sent in ajax, inside PHP无法在 PHP 中回显在 ajax 中发送的 POST 参数
【发布时间】:2018-10-27 14:14:11
【问题描述】:

我在 send 方法中向 index.php 发送两个参数。但是 PHP 返回一个错误“未定义的索引”。 回声 $_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");
  });

【问题讨论】:

    标签: javascript php ajax


    【解决方案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");
    });
    

    【讨论】:

      猜你喜欢
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多