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

菜鸟分享ajax基础

// 这是ajax最简单、最基本的知识 
<%@ 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 'AjaxGet.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">
	-->
	<script type="text/javascript" src="./js/util.js"></script>
  </head>
  
  <body><form action="" enctype="application/x-www-form-urlencoded"></form>
   <input type="button" value="AjaxGet测试" onclick="getAjax()"/>
   <input type="button" value="AjaxPost测试" onclick="postAjax()"/>
   <div id="content">
   </div>
  </body>
</html>
<script>
function getAjax(){
//创建xmlhttprequest实例
var xhr=getXMLHttpRequest();
//加载open方法
xhr.open("get","index.jsp?username=guoqianfang",true);
/*
open方法中共有5个参数,分别是method/url/async/user/password,常用的有3个参数,分别是method、url、async,
method:get、post,他们的区别是:get请求的参数是加载到url上的用?和&符号链接最大不能超过2k;post请求时
把参数不用加载到url上去,有安全性,但也可以加载到url上,而且也能获得到加载上的参数
url:可以是相对的也可以是绝对的地址
async:true(异步)、false(同步,一般不用),默认是true

*/

xhr.send();

/*
get请求时,不用设置xhr.setRequestHeader(header,value),send方法 的参数可以什么都不写也可以写成null,
如果send方法里要写了参数的话,必须设置xhr.setRequestHeader(header,value),会默认成post方法请求,而
且send方法里的参数获得不到
post请求时,必须设置xhr.setRequestHeader(header,value);

*/
//写调用函数
xhr.onreadystatechange=function(){
	//判断是否调用完成
	if(xhr.readyState==4){
		//判断服务器是否处理成功
		if(xhr.status==200){
			$("content").innerHTML=xhr.responseText;
		}
	}
}
}
function postAjax(){
var xhr=getXMLHttpRequest();
xhr.open("post","index.jsp",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send("username=guoqianfang");
xhr.onreadystatechange=function(){
	//判断是否调用完成
	if(xhr.readyState==4){
		//判断服务器是否处理成功
		if(xhr.status==200){
			$("content").innerHTML=xhr.responseText;
		}
	}
}
}
</script>

Util.js脚本
function $(id){
	return document.getElementById(id);
}
function getXMLHttpRequest(){
	var xhr;
	try{
		//IE浏览器
		xhr=new ActiveXObject("Micorsoft.XMLHTTP");
	}catch(error){
		try{
			//firefox/opera浏览器
			xhr=new XMLHttpRequest();
		}catch(e){
			return xhr;
		}
	}
	return xhr;
}