AJAX的基本实现步骤

来源:互联网 发布:淘宝天天特价秒杀 编辑:程序博客网 时间:2024/06/05 14:40

1.ajax是什么?

 AJAX 是一种用于创建快速动态网页的技术。即在不刷新网页的情况下,对网页的某部分进行更新。

2.ajax工作原理

  • 创建XMLHttpRequest对象
    为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject 。代码如下:
var xmlhttp;if (window.XMLHttpRequest){    // IE7及以上, Firefox, Chrome, Opera, Safari等浏览器      xmlhttp=new XMLHttpRequest();  }else{      //  IE6, IE5支持      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }
  • 向服务器发送请求
    如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("GET","ajax.jsp",true);xmlhttp.send();

这里的请求有两种,get和post,上面代码表示的是get,若是post,需使用setRequestHeader() 来添加 HTTP 头:

xmlhttp.open("POST","ajax.jsp",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("fname=张&lname=三");
  • 服务器响应
    这里填写的是需要出现的内容,即你想要得到的东西
document.getElementById("myDiv").innerText=xmlhttp.response;
  • onreadystatechange 事件
    当请求被发送到服务器时,我们需要执行一些基于响应的任务。
    每当 readyState 改变时,就会触发 onreadystatechange 事件。
    readyState 属性存有 XMLHttpRequest 的状态信息。分别表示为:
    0: 请求未初始化
    1: 服务器连接已建立
    2: 请求已接收
    3: 请求处理中
    4: 请求已完成,且响应已就绪

    当 readyState 等于 4 时,表示响应已就绪:

xmlhttp.onreadystatechange=function(){  if (xmlhttp.readyState==4 ){    document.getElementById("myDiv").innerText=xmlhttp.response;    }  }

附上整个代码:(主要是以jsp实现,可结合servlet实现web端的效果,此处只附上简单的jsp代码,代码已封装成可以多用,function ajax()中内容可以直接调用,而function loadText2()在不同需要下实现不同url和callback即可)

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>ajax</title><script type="text/javascript">    function ajax(params){        var xmlhttp;        if(window.XMLHttpRequest){            xmlhttp = new XMLHttpRequest();        }else{            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");        }        xmlhttp.onreadystatechange = function(){            if(xmlhttp.readyState == 4){                //输出响应结果                if(params.callback){                    params.callback(xmlhttp);                }            }        };        var method = params.method ? params.method : "GET";        var asynch = params.asynch ? true : params.asynch;        //打开连接        xmlhttp.open(method,params.url,params.asynch);        //判断是否为post方法        if(method == 'POST'){            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");        }        //判断是否有参数        if(params.params){            //假设params.params = {"userName":"张三","gender":"男"};            //转换成userName=张三&gengder=男            var p = [];            for (key in params.params){                p.push(key + "=" + params.params[key]);            }            xmlhttp.send(p.join("&"));        }else{            xmlhttp.send(null);        }    }    function loadText2(){        ajax({            //此处head.jsp是需要在点击之后呈现的内容的路径            url:"head.jsp",            callback:function(xmlhttp){                document.getElementById("ajax").innerText = xmlhttp.response;            }        });    }</script></head><body>   <p id = "ajax"></p>   <button type="button" onclick = "loadText2()">测试一下吧</button></body></html>
0 0