ajax详细解读
1 什么是ajax?
2 传统的web应用 3 使用ajax后的web应用 4 ajax的编程步骤
由于各版本浏览器的兼容性问题,所以获取ajax对象需要区分IE浏览器和非IE浏览器
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();//非IE
}else {
xhr = new ActiveXObject('Microsoft.XMLHttp');//IE
}
xhr.open('请求方式','请求地址','异步还是同步');
请求方式:get/post
请求地址:如果是get请求,请求参数需要添加到请求地址的后面
异步还是同步:true表示异步请求,false表示同步请求(ajax发出请求时,浏览器会锁定当前页面,直到ajax请求处理完毕)。
例子:xhr.open('get','send.do?username=tom',true);
服务器一般不需要返回完整的代码,只需要返回部分数据,比如一个简单的字符串、xml、json等。
xhr.onreadystatechange=function (){
if(xhr.readyState == 4){
//获得服务器返回的数据
var txt = xhr.responseText;
//dom操作
}
};
xhr.send(null);
5 ajax的get方式和post方式
window.onload = function(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();//非IE
}else {
xhr = new ActiveXObject('Microsoft.XMLHttp');//IE
}
xhr.open('get',true);
xhr.onreadystatechange=function (){
if(xhr.readyState == 4){
//获得服务器返回的数据
var txt = xhr.responseText;
//dom操作
}
};
xhr.send(null);
}
window.onload = function(){
var xhr = null;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();//非IE
}else {
xhr = new ActiveXObject('Microsoft.XMLHttp');//IE
}
xhr.open('get','send.do',true);
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');
xhr.onreadystatechange=function (){
if(xhr.readyState == 4){
//获得服务器返回的数据
var txt = xhr.responseText;
//dom操作
}
};
xhr.send('username=' + $F('username'));
}
6 发送get请求的编码问题
7 发送post请求的编码问题
8 jquery对ajax的支持 $.ajax({
type: "POST",url: 'send.do',dataType: "json",//json字符串
success: function(data) {//返回的数据
}
});
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |