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

原生ajax POST,解决Undefined index

原生ajax,POST请求:

var xhr=new XMLHttpRequest();
    xhr.open('POST','test.PHP',true);
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
                console.log('成功插入');
            if(xhr.status==200){
                console.log('响应成功');
                console.log('回调');
                console.log(xhr.responseText);
            }
        }
    }

    xhr.send("user=xianfeng");
<? echo $_POST['user']; ?>

但是服务端响应数据失败。

后来经过测试,是客户端发送请求到服务端的时候少写了响应报头。

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  • 认情况下,服务器对于客户端一无所知,不知道客户端的任何信息。
  • 在http协议中,请求主体被规定为放置传递到服务器的数据。
    那如何告诉服务端有关客户端的信息呢,所以就设计了一个请求头的概念,规定在这里放置一些客户端的信息。
  • cookie就是放置在这里,以在每次请求时发送给相关的域。
  • 请求头可以自定义,那么你就可以根据请求头的相关信息,在服务器端做一些特殊处理。

最后加上代码,再测试一次:

<script type="text/javascript"> var xhr=new XMLHttpRequest(); xhr.open('POST',true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ console.log('成功插入'); if(xhr.status==200){ console.log('响应成功'); console.log('回调'); console.log(xhr.responseText); } } } xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send("user=xianfeng"); </script>

成功返回post的结果。

原文地址:https://www.jb51.cc/ajax/161538.html

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

相关推荐