php post方法获取Ajax后台传来的数据失败,但是用php get方法却可以获取到。

时间:2021-05-02 19:01:05
这是html文档

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

    <script type="text/javascript">
        window.onload = function(){
           var btn = document.getElementById("btn");
           btn.onclick = function(){
               var xhr = null;
               if(window.XMLHttpRequest){
                   xhr = new XMLHttpRequest();
               }else{
                   xhr = new ActiveXObject("Microsoft.XMLHTTP");
               }

               var username = document.getElementById("username").value;
               var password = document.getElementById('password').value;

               var url = "post.php";

               xhr.open('post',url,true);
               xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

               var param = 'username='+username+'&password='+password;
               alert(param)
               xhr.send(param);

               xhr.onreadystatechange = function(){
                   if(xhr.readyState==4){
                       if(xhr.status==200){
                           var data = xhr.responseText;
                           console.log(data);
                           document.getElementById("content").innerHTML = data;
                       }
                   }
               }

           }

        }


    </script>

</head>
<body>
    <form>
        用户名: <input type="text" id="username"/>
        密码: <input type="password" id="password"/>
        <input type="button" value="提交" id="btn"/>

    </form>
<div id="content"></div>

</body>
</html>

这是 php 文档

<?php

header("Content-Type:text/html;charset=utf-8");

//$username = $_GET["username"];
//$password = $_GET["password"];

$username = $_POST['username'];
$password = $_POST['password'];


echo "用户名:".$username."密码:".$password;




?>

2 个解决方案

#1



               xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded ;charset=utf-8");

去掉红色的内容试试,不过就算content-type错,也不会把参数加到url上的,检查你的服务器是不是做了什么转换

Web开发学习资料推荐
ajax对象属性withCredentials
javascript生成二维码

#2


该回复于2017-11-20 15:09:54被管理员删除

#1



               xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded ;charset=utf-8");

去掉红色的内容试试,不过就算content-type错,也不会把参数加到url上的,检查你的服务器是不是做了什么转换

Web开发学习资料推荐
ajax对象属性withCredentials
javascript生成二维码

#2


该回复于2017-11-20 15:09:54被管理员删除