AJAX作為異步傳輸,局部刷新非常方便,用處很廣!
首先,對于AJAX的使用有4步:
1.創建AJAX對象
	var xmlHttp = new XMLHttpRequest();
2.建立連接 (‘提交方式',‘Url地址')
	xmlHttp.open('get','./AJAX_XML.xml');
3.判斷ajax準備狀態及狀態碼
xmlHttp.onreadystatechange = function(){    if (xmlHttp.readyState==4 && xmlHttp.status==200) {  }}4.發送請求
	xmlHttp.send(null);    //get方式參數為null,post方式,參數為提交的參數
以下以異步提交用戶名(輸入用戶名之后,異步提交后臺判斷,前臺立馬提示是否已注冊,不用提交時再判斷!)
GET方式提交
xx.html
<script type="text/javascript">window.onload=function(){  document.getElementById('username').onblur=function(){    var name=document.getElementById('username').value;    var req=new XMLHttpRequest();    req.open('get','4-demo.php?name='+name);    req.onreadystatechange=function(){      if(req.readyState==4 && req.status==200){        alert(req.responseText);      }    }    req.send(null);  //如果send()方法中沒有數據,要寫null  }}</script>	用戶名:  <input type="text" name="" id="username">
xx.php
<?phpprint_r($_GET);?>
1、 IE不支持中文
2、 =、&與請求的字符串的關鍵字相混淆。
POST提交
xx.html
<script type="text/javascript">window.onload=function(){  document.getElementById('username').onblur=function(){    var name=document.getElementById('username').value;    name=encodeURIComponent(name);    var req=new XMLHttpRequest();    req.open('post','5-demo.php?age='+20);    req.onreadystatechange=function(){      if(req.readyState==4 && req.status==200){        alert(req.responseText);      }    }  req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');    req.send('name='+name);    }}</script>	用戶名: <input type="text" name="" id="username">
xx.php
<?phpprint_r($_POST);print_r($_GET);?>
1、通過send()發送數據
2、必須設置setRequestHeader()將傳遞的參數轉成XML格式
3、post提交可以直接提交中文,不需要轉碼
4、post請求中的字符也會和URL中的&、=字符相混淆,所以建議也要使用encodeURIComponent()編碼
5、在POST提交的同時,可以進行GET提交
解決 IE不支持中文 =、&與請求的字符串的關鍵字相混淆 問題
在js中通過encodeURIComponent()進行編碼即可。
window.onload=function(){  document.getElementById('username').onblur=function(){    var name=document.getElementById('username').value;    name=encodeURIComponent(name);  //編碼    var req=new XMLHttpRequest();    req.open('get','4-demo.php?name='+name);    req.onreadystatechange=function(){      if(req.readyState==4 && req.status==200){        alert(req.responseText);      }    }    req.send(null);  //如果send()方法中沒有數據,要寫null  }}1、req.responseText:獲取返回的字符串
2、req.responseXML:按DOM結構獲取返回的數據
注意post/get兩種提交方式的區別!
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持VeVb武林網!
新聞熱點
疑難解答
圖片精選