1 Ajax(Asynchronous JavaScript and XML),异步的JavaScript与XML
2 Ajax中的一个重要对象是XMLHttpRequest。
3 使用Ajax准备向服务器端发送请求:
xmlHttpRequest.open("GET", "AjaxServlet", true);
示例
利用ajax 单击按钮刷新div
(1)
(2) JS
代码
注:XMLHTTPRequest对象在IE浏览器中和其他浏览器中实例化方式不一样
var xmlHttpRequest=null;//声明一个空的可以接收XMLHttpRequest对象
function ajaxSubmit()
{
if(window.ActiveXObject)
{
//IE浏览器
xmlHttpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{//除IE以外的其他浏览器
xmlHttpRequest=new XMLHttpRequest();
}
if(null!=xmlHttpRequest)
{
alert("invoked");
xmlHttpRequest.open("GET", "/LearnWeb_Test/myAjax1", true)
//关联好ajax回调函数
xmlHttpRequest.onreadystatechange=ajaxCallBack;
//向服务器发送数据
xmlHttpRequest.send();
}
}
function ajaxCallBack()
{
//回调函数发生4次
//alert("回调");
if(xmlHttpRequest.readyState==4)
{
if(xmlHttpRequest.status==200)
{
var responseTest=xmlHttpRequest.responseText;
document.getElementById("div").innerHTML=responseTest;
}
}
}
(3) 服务器端代码
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("invoked");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("i miss you father");
out.flush();
out.close();
}
4 禁用页面缓存,通过相应头设置。在服务器端设置
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
5 GET与POST的对比
(1) 以GET方式发送请求
var v1=document.getElementById("v1").value;
var v2=document.getElementById("v2").value;
xmlHttpRequest.open("GET", "/LearnWeb_Test/myAjax1?v1="+v1+"&v2="+v2, true)(2) 以POST方式请求
if (null != xmlHttpRequest)
{
var v1=document.getElementById("v1").value;
var v2=document.getElementById("v2").value;
xmlHttpRequest.open("POST", "/LearnWeb_Test/myAjax1", true)
//关联好ajax回调函数
xmlHttpRequest.onreadystatechange = ajaxCallBack;
//向服务器发送数据
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// 使用post方式提交,必须要加上如下一行
xmlHttpRequest.send("v1="+v1+"&v2="+v2);
}