日期:2014-05-16  浏览次数:20627 次

Ajax的简单应用(1)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'getAjax.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>

<body>

<input type="button" value="AjaxGet请求" onclick="getAjax()"/>
<div id="content"></div>

</body>
</html>
<script type="text/javascript" src="./js/util.js"></script>
<script>

//getAjax请求

//创建XMLHttpRequest对象

function getXhr() {

var xhr;

try {

//IE浏览器

xhr = new ActiveXObject("Microsoft.XMLHTTP");

} catch (err) {

try {

//firefox opera 等其他浏览器

xhr = new XMLHttpRequest();

} catch (er) {

alert("您的浏览器不支持ajax技术的操作,请您升级.....");

}



}



return xhr;

}

function getAjax(){
    
     //获取xhr对象
     var xhr = getXhr();
     //规定请求类型
 
     /*
     open(method,url,async)
         method:get ,post /get与post的区别总结出来
                /get 地址栏中显示? & 2k
                /post:url
        url:相对路径 也可以使绝对路径
     
        async:true异步 false 同步
     */
    
        xhr.open("get","main.jsp?username=123",true);
       
        //get请求 就不必要设置 xhr.setRequestHeader(header,value)
       
        //发送请求,如果是get请求send(参数)参数:必须是null或者xhr.send();
        //备注:如果xhr.send(参数);参数不为空情况下,会自动转换成post请求方式
        //您可以通过request.getMethod();方法获取请求的方式
        xhr.send();
        /*当发送请求时:readyState对象状态会自动改变并且有服务器端发送给客户端
        * readyState的每次改变都会自动处理onreadystatechanage事件
      
          readystate的值:
           0:未处理
           1:读取中
           2:已读取
           3:交互中
           4:完成
         值的每一次改变都会处理:onreadystatechana