【问题标题】:using POST in ajax in vanilla js在香草js中使用ajax中的POST
【发布时间】:2023-03-20 19:02:01
【问题描述】:

我正在尝试将发布请求发送到我的 PHP 文件,但它说的是未定义的索引。

我的 js 代码 -

document.getElementById("btn1").addEventListener('click', xh );

function xh(){
    xhr = new XMLHttpRequest();
    //xhr.open('GET', 'req.php?msg=hello bro', true);
    xhr.open('POST', 'req.php');
    xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');
    
    xhr.onprogress = function () {
       // document.getElementById("loading").classList.remove("dis");
    }
    xhr.onload = function () {          
        console.log(this.responseText);
    }
    
        xhr.send("msg=hello");        
    }

我的 PHP 代码 -

 <?php
        if(isset($_POST['msg'])){
            echo "set";
        }
        else{
            echo "not set";
        }
    ?>

我也尝试了服务器请求方法,但没有成功

它显示未设置,如果我尝试回显$_POST['msg'];,它会显示未定义索引'msg'

【问题讨论】:

  • 让自己的生活更轻松,并开始使用fetch api - 它是一个更简洁的 api,并且与 Promises 很好地结合

标签: javascript php ajax post


【解决方案1】:

而不是

xhr.getResponseHeader('Content-type', 'application/w-xxx-form-urlencoded');

你想设置请求头

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

阅读有关XHR 的更多信息。目前的方法是使用fetch()

fetch("req.php", {
  method: "POST",
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  body: "msg=hello"
}).then(response => response.text())
  .then(console.log)

【讨论】:

    猜你喜欢
    • 2020-10-20
    • 1970-01-01
    • 2016-12-11
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多