首先為大家分享了原生JavaScript實(shí)現(xiàn)Ajax代碼,供大家參考,具體內(nèi)容如下
var getXmlHttpRequest = function() { if (window.XMLHttpRequest) { //主流瀏覽器提供了XMLHttpRequest對(duì)象 return new XMLHttpRequest(); } else if (window.ActiveXObject) { //低版本的IE瀏覽器沒(méi)有提供XMLHttpRequest對(duì)象 //所以必須使用IE瀏覽器的特定實(shí)現(xiàn)ActiveXObject return new ActiveXObject("Microsoft.XMLHttpRequest"); }};var xhr = getXmlHttpRequest();xhr.onreadystatechange = function() { console.log(xhr.readyState); if (xhr.readyState === 3 && xhr.status === 200) { //獲取成功后執(zhí)行操作 //數(shù)據(jù)在xhr.responseText console.log(xhr.responseText); }};xhr.open("get", "data.php", true);xhr.send(""); 下面和大家分享幾種利用javascript實(shí)現(xiàn)原生ajax的方法。
實(shí)現(xiàn)ajax之前必須要?jiǎng)?chuàng)建一個(gè) XMLHttpRequest 對(duì)象。如果不支持創(chuàng)建該對(duì)象的瀏覽器,則需要?jiǎng)?chuàng)建 ActiveXObject,具體方法如下:
var xmlHttp; function createxmlHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp=new XMLHttpRequest(); } (1)下面使用上面創(chuàng)建的xmlHttp實(shí)現(xiàn)最簡(jiǎn)單的ajax get請(qǐng)求:
function doGet(url){ // 注意在傳參數(shù)值的時(shí)候最好使用encodeURI處理一下,以防出現(xiàn)亂碼 createxmlHttpRequest(); xmlHttp.open("GET",url); xmlHttp.send(null); xmlHttp.onreadystatechange = function() { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); } else { alert('fail'); } } } (2)使用上面創(chuàng)建的xmlHttp實(shí)現(xiàn)最簡(jiǎn)單的ajax post請(qǐng)求:
function doPost(url,data){ // 注意在傳參數(shù)值的時(shí)候最好使用encodeURI處理一下,以防出現(xiàn)亂碼 createxmlHttpRequest(); xmlHttp.open("POST",url); xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttp.send(data); xmlHttp.onreadystatechange = function() { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert('success'); } else { alert('fail'); } } } 以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。



















