原生ajax POST,解决Undefined index

前端之家收集整理的这篇文章主要介绍了原生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.f2er.com/ajax/161538.html

猜你在找的Ajax相关文章