AJAX – Asynchronous Javascript And XML—(異步JavaScript和XML)
原生ajax五步走
1.創建XMLHttpRequest對象—ajax
2.設置相關參數ajax.open(Type,Url,bol)
—參數一:發送請求的方式【GET/POST】;
—參數二:接收請求的文件路徑“index.php”
—GET請求時,將傳遞的參數寫到入瞭後面—“index.php?name=yohe&age=24”
—參數三:傳輸的模式【true/false】-true為異步傳輸-false為同步傳輸
3.設置傳遞的參數
—GET方法時,傳遞的參數直接拼接在url後面,所以ajax.send(null);
—POST方法時,ajax.send(“key1=val1&key2=val2”);
*4.POST方法時,需要設置請求頭文件,不然得不到傳回來的數據【GET方法時不需要】
—ajax.setRequestHeader(“Content-Type”,”application/x-www-form-urlencoded charset=utf-8”);
5.為ajax綁定事件,監聽當ajax的狀態碼【readyState】發生變化時,做出相應的操作
EG:
ajax.onreadystatechange = function(){ if(ajax.readyState == 4 && ajax.status ==200){ //這裡的responseText相當於successFun中的data【字符串】 //將json格式的字符串轉換成JSON數據方法:JSON.parse(str); console.log(ajax.responseText); } }
ps:在使用原生js的ajax方法時要加上
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded charset=utf-8");
全步驟代碼:
//創建XMLHttpRequest對象 var ajax = false; if(window.ActiveXObject){ ajax = new ActiveXObject("Microsoft.XMLHTTP"); }else{ ajax = new XMLHttpRequest(); } //創建請求-ajax.open()---GET方法 // ajax.open("GET","index.php?username=asd&sex=male&age=18",true); // ajax.send(null); // ajax.onreadystatechange = function(){ // console.log(ajax.readyState); // if(ajax.readyState ==4){ // console.log(ajax.responseText); // } // } //創建請求-ajax.open()---POST方法 $("#username").on("input",function(){ var user = $("#username").val(); ajax.open("POST","index.php",true); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); ajax.send("username="+user); ajax.onreadystatechange = function(){ console.log(ajax.readyState); if(ajax.readyState ==4){ console.log(ajax.responseText); if(!ajax.responseText){ $("#span").html("可用"); $("#span").css("color","blue"); }else{ $("#span").html("有重復的啦傻逼"); $("#span").css("color","red"); } } } })