使用AJAX异步获取数据

来源:互联网 发布:雷克萨斯 gs300h知乎 编辑:程序博客网 时间:2024/04/26 09:31
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
【导读】本文给出一个例子(使用AJAX异步获取数据),介绍如何去使用AJAX

AJAX这个名字看起来很神奇,我第一次见到它也被它吸引了,它是Asynchronous JavaScript and XML的简写,异步的JAVASCRIPT和XML,关于AJAX的介绍在网上的介绍太多了,我就不多那么多了,我的口才不好,没他们说的那么精彩,可以去http://zh.wikipedia.org/wiki/AJAX 看看,在这里我只是给大家一个例子,了解如何去使用AJAX

AJAX最有意思的地方就是可以不用刷新网页而可以和后台进行交互,不需要对页面进行刷新,实现网页与网页间的平滑过渡。使用AJAX不需要安装新的插件,只要求你的浏览器支持JAVASCRIPT。

首先你需要你个JAVASCRIPT中的对象XMLHttpRequest,它是AJAX的核心,我们都围绕着它做事,通过下面的代码可以获取一个:

if (window.XMLHttpRequest){

xmlObj = new XMLHttpRequest();

}else if (window.ActiveXObject){

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

}

我们通过这个对象的OPEN方法向服务发送请求,

该函数声明为XMLHttpRequest.open(String method, String URL, boolean asynchronous);

method是请求的方式,可以为GET和POST

URL是你要请求的资源

asynchronous是布尔类型,为true表示交互设置为异步

xmlObj.open("GET",URL,true);

xmlObj.send("");

调用send()(参数是空或是null)将会发起一次请求,

对于GET方式的请求,两次同样的请求将会得到相同的结果,

由于为将交互设置为异步方式,因此要为指定一个回调函数:

xmlObj.onreadystatechange = callBackFunction;

剩下的事就交给回调函数处理了。

有一点要注意了,用Servlet或JSP来响应异步请求时,

要设置reponse的contentType属性指明是XML格式:

response.setContentType("text/xml");

一切都准备好了,那我们现在来做一个简单的异步请求,并将请求返回的结果显示出来:

客户端:







发送请求



看这里!







以下是data.jsp

<%response.setContentType("text/xml");%>





Zjcfan

<<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击