最近开始想用AJAX来做项目了,所以开始学习AJAX.
ajax原理很简单,下面这个例子是我最初学习写的一个例子:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" >
<html >
<head >
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" >
<title >Simple XMLHttpRequest </title >
</head >
<body >
<form action="#" >
<input type="button" value="Start Basic Asynchronous Request" onclick="startRequest();"/ >
<input type="text" id="s"/ >
</form >
</body >
</html >
<script type="text/javascript" >
var xmlHttp;
//创建xmlHttp对象
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function startRequest(){
createXMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange; //回调函数
xmlHttp.open("GET", "aaa.txt", true);
xmlHttp.send(null);
}
function handleStateChange(){
if(xmlHttp.readyState == 1){
document.getElementById("s").value = "正在加载……";
}
if(xmlHttp.readyState == 2){
document.getElementById("s").value = "已加载!";
}
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){//成功加载
document.getElementById("s").value = xmlHttp.responseText;//返回aaa.txt文件的内容,实际应用中可以在servlet中把要输出的内容写入输出流.
}
}
}
</script >
至于实际应用中,最好使用一种框架或者封装的工具包,比如prototypes.js,但是ajax基本原理就这么简单。
Tags: ajax |
原创文章如转载,请注明:转载自:巴士飞扬-技术BLOG : http://www.busfly.net/
本文链接地址:http://www.busfly.net/post/sampel_ajax_src.html
如果你喜欢本文,请顶一下,支持我,你的支持是我继续发好文章的最大动力。谢谢。
好东西需要分享,快把本文发给你的朋友吧~!~