直接上代码了:
1、JS代码发起跨域请求
$.ajax({
type: "POST",url: "/UserAction.do?method=getJsonpCurrentInfo",
dataType:"jsonp",
jsonp: "jsonpcallback", //必须的参数,跟后台返回数据时指定的参数名称相同
success : function(json) {
alert(json);
},
error:function(data){
alert(data);
}
})
2、后台action代码 :
public void getJsonpCurrentInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
//ukInfoList 业务数据...
// code 业务数据 ....
// msg 业务数据...
JSONObject data = new JSONObject();
data.put("cssweb_type", "success");
data.put("cssweb_code", code);
data.put("cssweb_msg", msg);
data.put("certlist", ukInfoList);
printData_jsonp(request,response, data.toString());
}
//返回JSONP数据的方法
private void printData_jsonp(HttpServletRequest request, HttpServletResponse response, String data) {
String jsonp = request.getParameter("jsonpcallback");
String result = "" + data.toString() + "";
result = jsonp + "(" + result + ")";
try {
PrintWriter out = null;
try {
response.setContentType("text/json; charset=UTF-8");
out = response.getWriter();
out.write(result);
out.flush();
out.close();
} catch (IOException e) {
log.error("jsonp输出出错");
}
} catch (Exception e) {
e.printStackTrace();
}
}