您的位置:首页 > 编程语言 > Java开发

Java知识整理(二十二)之Ajax

2015-09-19 10:32 381 查看
Ajax(局部刷新):Asynchronous JavaScript and XML异步的JavaScript和XML

Ajax原理:

使用Ajax发送异步请求

1.获得Ajax对象(可单独在js文件中写,或者放在html的<script>中):
var xhr = getXhr();
function getXhr(){
var xhr = null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHttp');//针对IE
}
return xhr;
}

2.编写回调事件处理函数:
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
var txt =xhr.responseText;//out.print();
alert(txt);
}
};

3.创建请求-get:xhr.open('get','xx.do',true);

  创建请求-post:xhr.open('post','xx.do',true);

  xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');(添加消息头)

true:发送异步请求(发送请求时可做其他操作)false:发送同步请求(发送请求时不可做其他操作)

4.发送请求-get:xhr.send(null); get若要提交数据,在xhr.open的url后面追加(xx.do?name=value&name=value)

  发送请求-get:xhr.send(name=value&name=value...);

异步对象的属性和方法:open(method,url)创建请求,method请求类型get post

send():发送请求;readyState:请求的状态;status:服务器返回的响应;readyState==4表示Ajax获得服务器返回的所有数据

解决get请求乱码(2种方式):IE的Ajax对象使用GBK对参数编码,其他浏览器使用UTF-8编码,服务器默认ios-8859-1解码

1.指定字符集解码;tomcat修改conf/server.mxl:<Connector URIEncoding="utf-8">  

2.使用encodeURI对请求地址进行编码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax