在這里用2個案例,來說明jquery是怎樣來實(shí)現(xiàn)ajax通信的
案例環(huán)境:[ tomcat6.0, struts1 ]
* jquery的API,返回的都是jquery對象。
案例:
1)
load 方式請求ajax,返回值在div中顯示,載入遠(yuǎn)程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地址 傳遞到后臺的數(shù)組參數(shù) 后臺返回來的結(jié)果

$('#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細(xì)節(jié):
//控制細(xì)節(jié)

function doajax()
{

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

success: function(responseText)
{
$('#testja').html(responseText);
}
});
}
4)
$.ajaxSetup({...}) 全局設(shè)置ajax默認(rèn)選項,語法等同于
$.ajax({...})。
//全局設(shè)定ajax

$.ajaxSetup(
{
data: "param=456&aa=aaa"
});
//控制細(xì)節(jié)

function doajax()
{

$.ajax(
{ --------------------->
type: "post", 可以將$.ajax({...})中的設(shè)置,全部提到$.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();

// 回傳處理的結(jié)果,到之前頁面
response.getWriter().println(responseText); <------- 用這種方式將值 傳回給頁面
return null;
}
5) jquery實(shí)現(xiàn)ajax返回XML格式的數(shù)據(jù)。

function doajax_responseXML()
{

$.ajax(
{
type :"post",
url :"/ajax_jquery/ajax_jquery/testajax.do?method=doajax_responseXML",
dataType :"xml", //在這里設(shè)置返回數(shù)據(jù)的類型 text OR xml.
success :callback
});
}

function callback(responseXML)
{
var jqueryObj = $(responseXML); //將dom對象,轉(zhuǎn)化成JQuery對象
var message = jqueryObj.children(); //獲取其中的結(jié)點(diǎn);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
花-花 閱讀(3700)
評論(1) 編輯 收藏 所屬分類:
ajax_jquery