天天看点

js发送ajax post请求

先说一下使用步骤

1.创建XHR对象

let ajax = new XMLHttpRequest( );

2.监听XHR对象的状态改变事件

ajax .onreadystatechange = function(){

if( ajax .readyState===4){

(注:readyState===4 是完成)

if(ajax .status===200){ 完成且成功 }

else { 完成但失败 }

}

}

3.打开到服务器的连接

ajax.open(post,  url,  true)

这里要加上请求头

ajax.setRequestHeader('content-type','application/x-www-form-urlencoded');

要是中文编译content-type

4.发起请求消息

ajax.send(data )

注:顺序一定要注意 就按照这个顺序,send里的data不能为空 如果不传数据传null 

js代码

function inser(){
            var userName = '张文涛';
            var userTel = '15029193261';
            //1.创建ajax对象
            var ajax = new XMLHttpRequest();
            // 2.监听XHR对象的状态改变事件
            ajax.onreadystatechange = function (){
                if(ajax.readyState==4&&ajax.status==200){
                   console.log(ajax.responseText,'ajax.responseText')
                }
            }
            //3.连接服务器
            ajax.open('post','http://www.yuyue-keji.com:1222/jcwecaht/interface/constructionLogin',true);
            //设置请求头信息
            ajax.setRequestHeader('content-type','application/x-www-form-urlencoded');
            //4.发送请求
            ajax.send('userName='+userName+"&userTel="+userTel);
            
            
        }
           

最后inser()调用

继续阅读