赞
踩
有时开发项目需要用到Ajax,使用ajax就不免返回的数据是json,下面是一个java后端的list转成jsonArray返回前端开发
1.前端发送ajax请求,这里我使用了jquery的ajax,封装成一个公共的js工具类common.js,代码如下:
/** 本地用获取访问前缀
var comm_basepath_index = document.location.pathname.substring(1).indexOf("/");
var comm_basepath = document.location.pathname.substring(0,comm_basepath_index+1); */
/** 网络上获取访问前缀 */
var comm_basepath = document.location.origin;
if (!comm_basepath){
comm_basepath = document.location.protocol + "//" + document.location.host;
}
//项目名
var pn = document.location.pathname.substring(0,document.location.pathname.substring(1).indexOf("/")+1);
comm_basepath += pn;
sendAjax=function(url, dataType, data, successF){
$.ajax({
url: url,
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: data,
cache: false,
dataType: dataType,
success: successF
});
};
js调用该方法发送请求:
//加载出剩下的所有图片
function loadAllPic(){
//取得当前页数
var pageNo = $("#hPageNo").val();
var pageSize = $("#hPageSize").val();
//var pn = document.location.pathname.substring(0,document.location.pathname.substring(1).indexOf("/")+1);
var url = comm_basepath + "/doPhotoList.do";
var param = {"pageNo":pageNo, "pageSize":pageSize};
sendAjax(url, "JSON", param, function(data){
var html = '';
$.each(data, function(commentK,commentV) {
html += "<li style=\"display:none\">";
html += "<a href=\"photos/"+commentV["bigPath"]+"\" title=\"\">";
html += "<img src=\"photos/"+commentV["smallPath"]+"\" alt=\"\">";
html += "</a></li>";
});
$("#gallery ul").append(html);
$('#gallery a').lightBox();
});
}
2.action接收请求并返回json数组代码如下:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.struts2.ServletActionContext;
/**
* 公司相册控制类
* @author xm
*
*/
public class CompanyPhotoAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private ICompanyPhotoService companyPhotoServiceImpl = new CompanyPhotoServiceImpl();
private Integer pageNo;
private Integer pageSize;
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void doPhotoList() throws IOException{
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter pw = response.getWriter();
Page<CompanyPhotoVo> page = new Page<CompanyPhotoVo>();
try {
page = companyPhotoServiceImpl.doPhotoList(pageNo, pageSize);
} catch (Exception e) {
e.printStackTrace();
}
JSONArray json=JSONArray.fromObject(page.getList());
pw.print(json);
}
}
该步需要导入相关的jar包,如下图:
3.struts.xml配置
<action name="doPhotoList" method="doPhotoList" class="com.action.CompanyPhotoAction" />
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。