您的位置:首页 > 其它

AJAX——Introduction和最简单的AJAX例子

2015-01-06 14:31 190 查看
AJAX即“Asynchronous Javascript
And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。

AJAX不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。

使用Javascript向服务器提出请求并处理响应而不阻塞用户!核心对象XMLHTTPRequest。通过这个对象,您的 JavaScript 可在不重载页面的情况与WEB服务器交换数据。
AJAX 在浏览器与 Web 服务器之间使用异步数据传输(HTTP 请求),这样就可使网页从服务器请求少量的信息,而不是整个页面。

一个简单的AJAX的例子,实现从服务器传输信息:

testAjax.html:
<!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>Insert title here</title>
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;

try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {

// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的浏览器不支持AJAX!");
return false;
}
}
}

xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
document.getElementById("time1").innerHTML = xmlHttp.responseText;
document.myForm.time.value = xmlHttp.responseText;
}
}
xmlHttp.open("GET", "jsp/time.jsp", true);
xmlHttp.send(null);
}
</script>
</head>
<body>
<form name="myForm">
用户: <input type="text" name="username" onkeyup="ajaxFunction();" />
时间: <input type="text" name="time" id="time"/>
<p>time: <span id="time1"></span></p>
</form>
</body>
</html>
接收请求的jsp文件:
<%@ 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; char
4000
set=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String time = "20150106";
out.write(time);
%>
</body>
</html>
当我们在名称中输入信息是,就会返回20150106到页面中,而不用加载整个页面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AJAX