加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

原生ajax POST,解决Undefined index

发布时间:2020-12-16 03:33:45 所属栏目:百科 来源:网络整理
导读:原生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( '响应成功' ); conso

原生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的结果。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读