在这里用2个案例,来说明jquery是怎样来实现ajax通信的
案例环境:[ tomcat6.0, struts1 ]
* jquery的API,返回的都是jquery对象。
案例:
1)
load 方式请求ajax,返回值在div中显示,载入远程html文件代码并插入到DOM中。
ajax_2.jsp:

<%
@ page language="java" pageEncoding="UTF-8"%>
<html>
<head>
<script type="text/javascript" src="jquery-1.2.6-vsdoc-cn.js"></script>

<script type="text/javascript">
//用jquery处理ajax请求

function doajax()
{ ajax请求的url地址 传递到后台的数组参数 后台返回来的结果

$('#testja').load('/ajaxTest/jquery-ajax/testajax.do',
{param:456},function(responseText)
{
alert(responseText);
});
}
</script>
</head>

<body>
<a href="javascript:doajax();">测试jquery-ajax</a>
<div id="testja"></div>
</body>
</html>
2)
get/post 方式请求ajax,上述
doajax()代码可改写为:

<script type="text/javascript">
function doajax()
{

$.get('/ajaxTest/jquery-ajax/testajax.do',
{param:456},function(responseText)
{
$('#testja').html(responseText);
});
}
</script>
3)
$.ajax({...}) 更多的控制ajax细节:
//控制细节

function doajax()
{

$.ajax(
{
type: "post",
url: "/ajaxTest/jquery-ajax/testajax.do",
data: "param=456123&aa=aaa",

success: function(responseText)
{
$('#testja').html(responseText);
}
});
}
4)
$.ajaxSetup({...}) 全局设置ajax默认选项,语法等同于
$.ajax({...})。
//全局设定ajax

$.ajaxSetup(
{
data: "param=456&aa=aaa"
});
//控制细节

function doajax()
{

$.ajax(
{ --------------------->
type: "post", 可以将$.ajax({...})中的设置,全部提到$.ajaxSetup({...}),更加通用。但必须至少保留$.ajax({...})
url: "/ajaxTest/jquery-ajax/testajax.do",
//data: "param=456123&aa=aaa",

success: function(responseText)
{
$('#testja').html(responseText);
}
});
}
AjaxTestAction:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)

throws Exception
{
String str1 = request.getParameter("param");
StringBuffer sb = new StringBuffer(str1);
sb.append("+123");
String responseText = sb.toString();

// 回传处理的结果,到之前页面
response.getWriter().println(responseText); <------- 用这种方式将值 传回给页面
return null;
}
5) jquery实现ajax返回XML格式的数据。

function doajax_responseXML()
{

$.ajax(
{
type :"post",
url :"/ajax_jquery/ajax_jquery/testajax.do?method=doajax_responseXML",
dataType :"xml", //在这里设置返回数据的类型 text OR xml.
success :callback
});
}

function callback(responseXML)
{
var jqueryObj = $(responseXML); //将dom对象,转化成JQuery对象
var message = jqueryObj.children(); //获取其中的结点;children("expr")
var text = message.text();
$('#testja').html(text);
}
后台Action中组装一个<message>XML格式,并且注意
response.setContentType("text/xml;charset=utf-8");
posted on 2009-01-08 17:41
花-花 阅读(3696)
评论(1) 编辑 收藏 所属分类:
ajax_jquery