核心提示:原生ajax ,POST请求:var xhr=new XMLHttpRequest();xhr.open(POST,test.php,true);xhr.onreadystatechange=func...
原生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");
但是服务端响应数据失败。
后来经过测试,是客户端发送请求到服务端的时候少写了响应报头。
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
默认情况下,服务器对于客户端一无所知,不知道客户端的任何信息。 在http协议中,请求主体被规定为放置传递到服务器的数据。
那如何告诉服务端有关客户端的信息呢,所以就设计了一个请求头的概念,规定在这里放置一些客户端的信息。 cookie就是放置在这里,以在每次请求时发送给相关的域。 请求头可以自定义,那么你就可以根据请求头的相关信息,在服务器端做一些特殊处理。
最后加上代码,再测试一次:
<script type="text/javascript"> 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.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send("user=xianfeng"); </script>
成功返回post的结果。