Ajax技术
Ajax概述Ajax (Asynchronous JavaScript And XML)是一种浏览器无需刷新当前页面就能与服务器通讯的技术。 Ajax原理与技术Ajax的实现原理:在页面中触发一个事件,创建一个XMLHttpRequest异步通讯对象,把Http方法(get/post)、目标URL地址与服务器建立连接、发送数据以及监听XMLHttpRequest对象的状态变化以便请求发送情况。此时在页面中用户可以继续进行界面的交互,当服务器发送回响应内容并在请求完成时调用callback()函数,在函数中解析响应内容并通过dom规则动态地更新页面部分内容。 实现Ajax异步通讯的步骤:
/** 1、 创建XMLHttpRequest对象 */
var xmlhttp;
function createXMLHttpRequest(){
if (window.XMLHttpRequest){// code for IE7+,Firefox,Chrome,Opera,Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6,IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
/** 2、 设定onreadystatechange属性的回调方法 */
响应内容有: responseText/ responseXML
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4){//当 readyState 等于 4 且状态为 200 时,表示响应已就绪
if (xmlhttp.status == 200){
document.getElementById("div1").innerHTML = xmlhttp.responseText;
}
}
}
/** 3、 调用open(method,url,async)方法 */
//get请求
xmlhttp.open("GET","timeServlet?t=" + Math.random(),true);
xmlhttp.send(null);
//post请求
xmlhttp.open("POST","timeServlet",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//此句代码应该在open方法之后,send方法之前
xmlhttp.send("fname=Bill&lname=Gates");
/** 4、 调用send(data)方法 */
将请求发送到服务器。
data:将要传递给服务器的字符串(格式为:param1=xxx¶m2=yyy)。若是 GET 请求,则不会发送任何数据,给 send 方法传递 null 即:request.send(null);当向send()方法提供参数时,要确保open()中指定的方法是POST,如果没有数据作为请求体的一部分发送,则使用null。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |