ajax基础学习

AJAX即“Asynchronous JavaScript and XML”,意思是异步JavaScript和XML,是指一种创建交互式网页的网页开发技术。

  虽然现在很少有人去自己手动写AJAX,大多数都用封装好的AJAX,但我觉得初学者还是应该从最原始的AJAX开始学习,这样才能掌握AJAX的核心。现在各种博客上讲解AJAX的比较多,但大多数都是只讲AJAX的前端部分,或者是只讲解一部分功能,并没有完成的实例。在这篇随笔里我将通过实例来全面讲解AJAX的基础应用,其中也包括后台代码实现部分。

实例一:点击一个按钮,然后将信息显示到指定的div内。

  1、创建一个JAVA web工程,命名为AjaxTest。在webRoot创建一个HTML页面,命名为FirstTest.html,FirstTest.html代码如下:

<html>
<head>
<title>FirstTest.html</title>
<script language="javascript">
function onclickAjax(){

}
</script>
</head>

<body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="testid">
</div>
</body>
</html>
复制代码
<html>
<head>
<title>FirstTest.html</title>
<script language="javascript">
function onclickAjax(){

}
</script>
</head>

<body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="testid">
</div>
</body>
</html>
复制代码

   在上面代码中给input绑定了点击事件onclickAjax(),这个onclickAjax()方法就是要实现Ajax的JS方法。

  2、实现onclickAjax方法

  为了方便理解,我给AJAX统一了一个流程,要想实现AJAX,就要按照以后步骤走:

  (1)创建XMLHttp对象。(2)设置请求方式。(3)调用回调函数。(4)发送请求。

  下面详细解释这4个步骤。

  (1)创建XMLHttp对象:XMLHttp对象用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

  创建XMLHttp对象的语法是:var xmlHttp=new XMLHttpRequest();如果是IE5或者IE6浏览器,则使用ActiveX对象,创建方法是:

var xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

  一般我们手写AJAX的时候,首先要判断该浏览器是否支持XMLHttpRequest对象,如果支持则创建该对象,如果不支持则创建ActiveX对象。JS代码如下:

var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
复制代码
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
复制代码

   (2)设置请求方式:在WEB开发中,请求有两种形式,一个是get 一个是post,所以在这里需要设置一下具体使用哪个请求,XMLHttpRequest对象的open()方法就是来设置请求方式的。

  open():

    功能:规定请求的类型、URL 以及是否异步处理请求。

    参数:参数1,设置请求类型(GET 或 POST),GET与POST的区别请自己百度一下,这里不做解释;

         参数2,文件在服务器上的位置;

         参数3,是否异步处理请求,是为true,否为false。

  具体的JS代码实现如下:

xmlHttp.open("POST","test.do?method=ajaxTest&&msg="+new Date(),true);
xmlHttp.open("POST","test.do?method=ajaxTest&&msg="+new Date(),true);

  在上段代码中,请求的名字是:"test.do?method=ajaxTest&&msg="+new Date(),后面有个new Date(),这里主要是防止缓存问题,如果是不段的更新页面内容,那么很可能就会出现点击按钮后内容页不改变,因为如果没有后面的msg=new Date()那么我们每一次发送的请求都是一样的,这样很可能就导致了缓存问题。所以需要在请求后面加上msg=new Date(),这样保障了每次的请求都不一样,避免缓存问题。

  (3)回调函数:

  如果在上一步中open方法的第三个参数选择的是true,那么当前就是异步请求,这个时候需要写一个回调函数,xmlHttp对象有一个onreadystatechange属性,这个属性返回的是一个匿名的方法,所以回调函数就在这里写xmlHttp.onreadystatechange=function{},function{}内部就是回调函数的内容。所谓回调函数,就是请求在后台处理完,再返回到前台所实现的功能。在这个例子里,我们的回调函数要实现的功能就是接收后台处理后反馈给前台的数据,然后将这个数据显示到指定的div上。因为从后台返回的数据可能是错误的,所以在回调函数中首先要判断后台返回的信息是否正确,如果正确才可以继续执行。代码如下:

if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
document.getElementById("testid").value=xmlHttp.responseText;//将信息显示到页面
}else{
alert("AJAX服务器返回错误!");
}
}
复制代码
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
document.getElementById("testid").value=xmlHttp.responseText;//将信息显示到页面
}else{
alert("AJAX服务器返回错误!");
}
}
复制代码

  在上面代码中,xmlHttp.readyState是存有XMLHttpRequest 的状态。从 0 到 4 发生变化。0: 请求未初始化。1: 服务器连接已建立。2: 请求已接收。3: 请求处理中。4: 请求已完成,且响应已就绪。所以这里我们判断只有当xmlHttp.readyState为4的时候才可以继续执行。

  xmlHttp.status是服务器返回的结果,其中200代表正确。404代表未找到页面,所以这里我们判断只有当xmlHttp.status等于200的时候才可以继续执行。

  document.getElementById("testid").value=xmlHttp.responseText;这段代码就是回调函数的核心内容,就是获取后台返回的数据,然后将这个数据赋值给id为testid的div。xmlHttp对象有两个属性都可以获取后台返回的数据,分别是:responseText和responseXML,其中responseText是用来获得字符串形式的响应数据,responseXML是用来获得 XML 形式的响应数据。至于选择哪一个是取决于后台给返回的数据的,这个例子里我们只是显示一条字符串数据所以选择的是responseText。responseXML将会在以后的例子中介绍。

  (4)发送请求:发送请求是调用xmlHttp对象的send()方法。代码如下:

xmlHttp.send();
xmlHttp.send();

  综合以上讲解,整个FirstTest.html页面的代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>FirstTest.html</title>
<script language="javascript">
function onclickAjax(){
var xmlHttp;
//分浏览器创建XMLHttp对象
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
//设置请求类型
xmlHttp.open("POST","test.do?method=ajaxTest&&msg="+new Date(),true);
//回调函数
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
document.getElementById("testid").value=xmlHttp.responseText;
}else{
alert("AJAX服务器返回错误!");
}
}
}
//发送请求
xmlHttp.send();
}
</script>
</head>

<body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="testid">
</div>
</body>
</html>
复制代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>FirstTest.html</title>
<script language="javascript">
function onclickAjax(){
var xmlHttp;
//分浏览器创建XMLHttp对象
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
//设置请求类型
xmlHttp.open("POST","test.do?method=ajaxTest&&msg="+new Date(),true);
//回调函数
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
document.getElementById("testid").value=xmlHttp.responseText;
}else{
alert("AJAX服务器返回错误!");
}
}
}
//发送请求
xmlHttp.send();
}
</script>
</head>

<body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="testid">
</div>
</body>
</html>
复制代码

   3、后台部分

  这个例子的后台部分使用JAVA来写,主要应用了struts1框架。

  (1)struts-config文件:

<struts-config>
<form-beans />
<action-mappings>
<action path="/test" type="com.test.controller.AjaxController" parameter="method" scope="request">
</action>
</action-mappings>
<message-resources parameter="com.test.controller.ApplicationResources" />
</struts-config>
复制代码
<struts-config>
<form-beans />
<action-mappings>
<action path="/test" type="com.test.controller.AjaxController" parameter="method" scope="request">
</action>
</action-mappings>
<message-resources parameter="com.test.controller.ApplicationResources" />
</struts-config>
复制代码

  (2)在包com.test.controller包下创建类AjaxController,并继承DispatchAction,重写execute方法并将该方法命名为ajaxTest。该方法代码如下:

public ActionForward ajaxTest(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String msg="第一个AJAX小程序";
response.getWriter().write(msg);
return null;
}
复制代码
public ActionForward ajaxTest(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String msg="第一个AJAX小程序";
response.getWriter().write(msg);
return null;
}
复制代码

  至此后台代码完成。

实例二:Ajax返回Json在Java中的实现

  在上一个随笔中,介绍AJAX的一个简单实例,在这篇中主要是说一下使用Json来将后台取得的数据显示到前台页面。可以说这种方法应该是实现无刷新分页的基础,而且在开发过程中经常被用到。这里的后台部分由JAVA来实现。

  这个例子也在上一篇中那个项目中实现。新建一个SecondTest.html页面,定义一个按钮,并给这个按钮绑定事件ajaxJson()。在JS中实现AJAX,这里的AJAX相对于上一篇中的,我做了简单的封装,将原有的代码分成三个方法,分别是create()、callback()、run()。

  create方法是用来创建XMLHttp对象的,callback是用来实现回调函数的,run方法是核心方法。具体代码如下:

  create():

function create(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
}
复制代码
function create(){
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else if(window.ActiveXObject){
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
}
复制代码

  callback():

function callback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//要实现的操作
}else{
alert("AJAX服务器返回错误!");
}
}
}
复制代码
function callback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
//要实现的操作
}else{
alert("AJAX服务器返回错误!");
}
}
}
复制代码

  run():

function run(url){
create();
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=callback;
xmlHttp.send();
}
function run(url){
create();
xmlHttp.open("POST",url,true);
xmlHttp.onreadystatechange=callback;
xmlHttp.send();
}

  以上三个方法写好后,在ajaxJson()方法中直接调用run方法并将请求当参数传入进去。代码如下:

function ajaxJson(){
run("test.do?method=jsonTest&&msg="+new Date());
}
function ajaxJson(){
run("test.do?method=jsonTest&&msg="+new Date());
}

  在AjaxController类的中新建jsonTest方法,在JAVA中实现Json是需要Json架包的,Json的架包有:json-lib-2.3-jdk15.jar,ezmorph-1[1].0.6.jar,commons-logging-tests.jar,commons-logging-api-1.1.1.jar,commons-logging-adapters-1.1.1.jar,commons-logging-1.1.1-sources.jar,commons-logging-1.1.1-javadoc.jar,commons-logging-1.1.1.jar,commons-lang.jar,commons-collections-3[1].2.1.jar,commons-beanutils-core.jar,commons-beanutils-bean-collections.jar,commons-beanutils.jar。看着有点多哈,可以自己去CSDN上面找,我试着删掉一些,但发现少了会不好使,所以为了保险还是把这些都加进去吧。

  在开发过程中一般数据都是从数据库中取出来的,习惯性的我们会在程序中将取出的数据存到List中,而Json架包中正好有封装好的方法能将List转换为Json。在这个例子中我们自己制造一些假数据放到List中,然后再将List转换为Json,再返回给前台。代码如下:

public ActionForward jsonTest(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//制造假数据
ArrayList<UserModel> list=new ArrayList<UserModel>();
UserModel user1=new UserModel();//用户对象1
user1.setUserId(1);
user1.setUserName("哈哈");
user1.setUserSex("男");
list.add(user1);

UserModel user2=new UserModel();//用户对象2
user2.setUserId(2);
user2.setUserName("呵呵");
user2.setUserSex("女");
list.add(user2);
//将List转化为JSON
JSONArray json=JSONArray.fromObject(list);
//设置编码
response.setCharacterEncoding("gbk");
//写入到前台
response.getWriter().write(json.toString());
return null;
}
复制代码
public ActionForward jsonTest(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//制造假数据
ArrayList<UserModel> list=new ArrayList<UserModel>();
UserModel user1=new UserModel();//用户对象1
user1.setUserId(1);
user1.setUserName("哈哈");
user1.setUserSex("男");
list.add(user1);

UserModel user2=new UserModel();//用户对象2
user2.setUserId(2);
user2.setUserName("呵呵");
user2.setUserSex("女");
list.add(user2);
//将List转化为JSON
JSONArray json=JSONArray.fromObject(list);
//设置编码
response.setCharacterEncoding("gbk");
//写入到前台
response.getWriter().write(json.toString());
return null;
}
复制代码

  后台部分写完了,现在前台SecondTest.html页面需要接收后台反馈来的数据,这个时候就需要在回调函数中接收Json数据。JS代码如下:

//回调函数
function callback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var xmlDoc=xmlHttp.responseText;
var data=eval(xmlDoc);
alert(data[0].userId+","+data[0].userName+","+data[0].userSex);
alert(data[1].userId+","+data[1].userName+","+data[1].userSex);
}else{
alert("AJAX服务器返回错误!");
}
}
}
复制代码
//回调函数
function callback(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var xmlDoc=xmlHttp.responseText;
var data=eval(xmlDoc);
alert(data[0].userId+","+data[0].userName+","+data[0].userSex);
alert(data[1].userId+","+data[1].userName+","+data[1].userSex);
}else{
alert("AJAX服务器返回错误!");
}
}
}
复制代码

  以上就完成了Ajax返回Json在Java中的实现。

原文地址:https://www.cnblogs.com/tfl-511/p/6086093.html