ajax 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
在js中使用ajax请求一般包含三个步骤:
创建xmlhttp对象
发送请求:包括打开链接、发送请求
处理响应
在不使用任何的js框架的情况下,要想使用ajax,可能需要向下面一样进行代码的编写
<span style="font-size:14px;">var xmlhttp = xmlhttpcreate();//创建对象
xmlhttp.onreadystatechange = function(){//响应处理
if(xmlhttp.readystate == 4){
console.info("response finish");
if(xmlhttp.status == 200){
console.info("reponse success");
console.info(xmlhttp.responsetext);
}
}
}
xmlhttp.open("get","testservlet",true);//打开链接
xmlhttp.send(null);//发送请求
function xmlhttpcreate() {
var xmlhttp;
try {
xmlhttp = new xmlhttprequest;// ff opera
} catch (e) {
try {
xmlhttp = new activexobject("msxml2.xmlhttp");// ie
} catch (e) {
try {
xmlhttp = new activexobject("microsoft.xmlhttp");
} catch (e) {
}
}
}
return xmlhttp;
}
console.info(xmlhttpcreate());</span>
如果在比较复杂的业务逻辑里面使用这种ajax请求,会使得代码很臃肿,不方便重用,并且可以看到,可能在服务器响应成功后要处理一个业务逻辑操作,这个时候不得不把操作写在onreadystatechage方法里面。
为了方便代码的重用我们可以做出如下处理;
服务器响应成功后,要处理的业务逻辑交给开发人员自己处理
对请求进行面向对象的封装
处理之后看起来应该像下面这个样子:
<pre code_snippet_id="342814" snippet_file_name="blog_20140513_2_2489549" name="code" class="javascript">window.onload = function() {
document.getelementbyid("hit").onclick = function() {
console.info("开始请求");
ajax.post({
data : 'a=n',
url : 'testservlet',
success : function(reponsetext) {
console.info("success : "+reponsetext);
},
error : function(reponsetext) {
console.info("error : "+reponsetext);
}
});
}
}
var ajax = {
xmlhttp : '',
url:'',
data:'',
xmlhttpcreate : function() {
var xmlhttp;
try {
xmlhttp = new xmlhttprequest;// ff opera
} catch (e) {
try {
xmlhttp = new activexobject("msxml2.xmlhttp");// ie
} catch (e) {
try {
xmlhttp = new activexobject("microsoft.xmlhttp");
} catch (e) {
}
}
}
return xmlhttp;
},
post:function(jsonobj){
ajax.data = jsonobj.data;
ajax.url = jsonobj.url;
//创建xmlhttp对象,打开链接、请求、响应
ajax.xmlhttp = ajax.xmlhttpcreate();
ajax.xmlhttp.open("post",ajax.url,true);
ajax.xmlhttp.onreadystatechange = function(){
if(ajax.xmlhttp.readystate == 4){
if(ajax.xmlhttp.status == 200){
jsonobj.success(ajax.xmlhttp.responsetext);
}else{
jsonobj.error(ajax.xmlhttp.responsetext);
}
}
}
ajax.xmlhttp.send(ajax.data);
}
};
以上就是javascript实现ajax请求步骤用法实例详解的详细内容。