Heim  >  Artikel  >  Web-Frontend  >  javascript实现原生ajax的几种方法介绍_javascript技巧

javascript实现原生ajax的几种方法介绍_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:22:101061Durchsuche

自从javascript有了各种框架之后,比如jquery,使用ajax已经变的相当简单了。但有时候为了追求简洁,可能项目中不需要加载jquery这种庞大的js插件。但又要使用到ajax这种功能该如何办呢?下面和大家分享几种利用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');
}
}
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn