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