JSONP

阅读更多
JSONP主要代码:

StringBuilder result = new StringBuilder(json.toString());				
String callback = request.getParameter("callback");
						
if(callback!=null && callback.trim() != ""){			
							result.insert(0, '(');
							result.insert(0, callback);
							result.append(")");
						
}

printJson(request, response, result.toString());


其中json是后台处理后的json对象,包含了要返回至前台的各种数据。


printJson(request, response, result.toString());用于向前台打印json对象数据。
public void printJson(HttpServletRequest request, HttpServletResponse response, String result) {
		try {
			response.setContentType("text/html;charset=utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			String var = request.getParameter("var");
			if (StringUtils.isNotBlank(var)) {
				result = new StringBuilder("var ").append(var).append("=").append(result).append(";").toString();
			}
			byte[] data = result.getBytes("utf-8");
			response.setContentLength(data.length);
			response.getOutputStream().write(data, 0, data.length);
		} catch (IOException e) {
			log.error("print result error!", e);
		}
	}


         后台构建数据过程:  
           
JSONObject root = new JSONObject();
		JSONArray arr = new JSONArray();
		for(){
			JSONObject o = new JSONObject();
			o.append("title", video.getTtitle());
			arr.put(o)
		}
		root.append("status", 1);
		root.append("msg","");
		root.append("data",arr);

要返回的json数据
{"status":1,"statusText":"数据信息","data":[{title:"sdfsfd",vid:2342,pid:234324,url:"",cid,"",actor:"",img:""},{}.............]}

你可能感兴趣的:(json,callback)