原生 JS Ajax,GET和POST 請(qǐng)求實(shí)例代碼

字號(hào):


    這篇文章主要介紹了原生 JS Ajax,GET和POST 請(qǐng)求實(shí)例代碼的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下
    javascript/js的ajax的GET請(qǐng)求代碼如下所示:
    <script type="text/javascript"> 
    /* 創(chuàng)建 XMLHttpRequest 對(duì)象 */
    var xmlHttp; 
    function GetXmlHttpObject(){ 
    if (window.XMLHttpRequest){ 
     // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    }else{// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    return xmlhttp; 
    } 
    // -----------ajax方法-----------// 
    function getLabelsGet(){ 
    xmlHttp=GetXmlHttpObject(); 
    if (xmlHttp==null){ 
     alert('您的瀏覽器不支持AJAX!'); 
     return; 
    } 
    var id = document.getElementById('id').value; 
    var url="http://www.Leefrom.com?id="+id+"&t/"+Math.random(); 
    xmlHttp.open("GET",url,true); 
    xmlHttp.onreadystatechange=favorOK;//發(fā)送事件后,收到信息了調(diào)用函數(shù) 
    xmlHttp.send(); 
    }
    function getOkGet(){ 
    if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){ 
     // 本地提示:加載中 
    } 
    if (xmlHttp.readyState==4 && xmlHttp.status==200){ 
     var d= xmlHttp.responseText; 
     // 處理返回結(jié)果 
    } 
    } 
    </script>
    javascript/js的ajax的POST請(qǐng)求:
    <script type="text/javascript"> 
    /* 創(chuàng)建 XMLHttpRequest 對(duì)象 */
    var xmlHttp; 
    function GetXmlHttpObject(){ 
    if (window.XMLHttpRequest){ 
    // code for IE7+, Firefox, Chrome, Opera, Safari 
    xmlhttp=new XMLHttpRequest(); 
    }else{// code for IE6, IE5 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    return xmlhttp; 
    } 
    // -----------ajax方法-----------// 
    function getLabelsPost(){ 
    xmlHttp=GetXmlHttpObject(); 
    if (xmlHttp==null){ 
    alert('您的瀏覽器不支持AJAX!'); 
    return; 
    } 
    var url="http://www.lifefrom.com/t/"+Math.random(); 
    xmlhttp.open("POST",url,true); 
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); 
    xmlhttp.send(); 
    xmlHttp.onreadystatechange=getLabelsOK;//發(fā)送事件后,收到信息了調(diào)用函數(shù) 
    } 
    function getOkPost(){ 
    if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){ 
    // 本地提示:加載中/處理中 
    } 
    if (xmlHttp.readyState==4 && xmlHttp.status==200){ 
    var d=xmlHttp.responseText; // 返回值 
    // 處理返回值 
    } 
    } 
    </script>
    注意:XMLHttpRequest 是 AJAX 的基礎(chǔ),在創(chuàng)建 XMLHttpRequest 對(duì)象時(shí),必須與你寫的ajax方法在同一個(gè)‘<script></script>'標(biāo)簽中!否則ajax請(qǐng)求會(huì)出錯(cuò),并無(wú)法返回?cái)?shù)據(jù)。 javascript/js的ajax的POST/GET請(qǐng)求。
    以上所述是小編給大家介紹的原生 JS Ajax,GET和POST 請(qǐng)求實(shí)例代碼的相關(guān)知識(shí),希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。