天天看點

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()調用

繼續閱讀