原生javascript中的的AJAX寫法

js中ajax get請求的寫法

var xhr=new XMLHttpRequest();
            xhr.open('get','請求地址')
            xhr.send();
            xhr.onreadystatechange=function () {
                if (xhr.readyState==4) {
                    // console.log(xhr.responeText
                }
            }

js中post請求的寫法

var xhr = new XMLHttpRequest();
xhr.open('post',"請求地址",true);
// 如果是post請求 必須加上請求頭
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("userName="+user.value+'&passWord='+pass.value);
xhr.onreadystatechange =function(){
 if (xhr.readyState==4) {
 var obj = JSON.parse(xhr.responseText);
 console.log(obj.responseCode);
 if (obj.responseCode=="0") {
 window.location.href = "denglu.html"
 }
 }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章