jQuery遍歷JSON對象,直接看代碼:
本文在ajax中調用struts2 action ,查詢數據庫,然後返回字符串,演示返回script,text,json類型的數據的用法
本文相關代碼下載在
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2011年資料/jQuery教程資料/jQuery調用struts2/
一。返回script和text時代碼都一樣
- ajax-jquery.js
- function commonAjax(oper,prod,url){
- oper.bind("change",function(){comJquery(oper,prod,url)});
- prod.bind("change",function(){comJquery(oper,prod,url)});
- }
- function comJquery(oper,prod,url){
- var prodId=prod.val();
- if(oper.val()!=''&&prod.val()!=''&&prod.val()!=0&&prod.val()!=-1){
- jQuery.ajax({
- url : url,
- data : {productId : prodId},
- type : "post",
- cache : false,
- dataType : "script"或者"text",
- success:callback
- });
- }else{
- $("#company").html('');
- }
- }
-
- function callback(data){
- $("#company").html(data);
- }
-
-
- jsp頁面調用ajax js(不管返回什麼類型,調用的代碼都一樣)
- <script type="text/javascript" src="script/jquery.js"></script>
- <script type="text/javascript" src="script/json2.js"></script>
- <script type="text/javascript" src="script/ajax-jquery.js"></script>
-
- var op=$("#cbApplySubmit_changeApplyFormBO_operationId");
- var pr=$("#cbApplySubmit_changeApplyFormBO_productId");
- var url="${contextPath}/assets/businessChange/ajaxGetCompany.do";
- commonAjax(op,pr,url);
-
-
-
- struts2 action
-
- private Integer productId;
- private IProductMng productMng; // 通過spring注入的service
-
- // get set
-
- public void ajaxGetCompany() throws Exception {
- ProductBO prod = productMng.loadProduct(productId);
- Integer companyId = prod.getCompanyId();
- CompanyBO comp = productMng.loadCompany(companyId);
- String message = "事業部為:" + comp.getName();
- sendMsg(message);
- }
-
- public void sendMsg(String content) throws IOException{
- HttpServletResponse response = ServletActionContext.getResponse();
- response.setCharacterEncoding("UTF-8");
- response.getWriter().write(content);
- }