微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 无法在ajax请求中获取PHP中的$_POST值

这是我的index.html

<script>
    var xml = new XMLHttpRequest();
    xml.onreadystatechange = function(){
        if (xml.readyState === 4 && xml.status === 200) {
            console.log(xml.responseText);
        }
    }
    xml.open("POST", "ajax.PHP", true);
    var data = new FormData();
    data.append("name","Sahan");
    xml.send(data);
</script>

这是我的ajax.PHP

<?PHP
echo "Hello " . $_POST["name"];
?>

当我在我的localhost上运行这个结果时

Notice: Undefined index: name in C:\xampp\htdocs\chat\ajax.PHP on line 2
Hello

但是当我使用JQuery时它正在正常工作……

我的问题是如何在没有JQuery的情况下使用JavaScript发送ajax ..?

解决方法:

当您对发布数据使用ajax时,您必须传递正确的标头信息以及请求

<script>
    var xml = new XMLHttpRequest();
    xml.onreadystatechange = function(){
        if (xml.readyState === 4 && xml.status === 200) {
            console.log(xml.responseText);
        }
    }
    xml.open("POST", "ajax.PHP", true);
    //Send the proper header @R_461_4045@ion along with the request
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    /*var data = new FormData();
    data.append("name","Stackoverflow");*/
    xml.send("name=Stackoverflow");
</script>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐