js 跨域访问实例
2016-04-08 13:24
501 查看
直接上代码了:
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();
}
}
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();
}
}
相关文章推荐
- JQuery1——基础($对象,选择器,对象转换)
- java-用HttpURLConnection发送Http请求.
- Android学习笔记(二九):嵌入浏览器
- Android java 与 javascript互访(相互调用)的方法例子
- JavaScript演示排序算法
- javascript实现10进制转为N进制数
- 最后一次说说闭包
- Ajax
- $.ajax()方法详解
- jQuery ajax - ajax() 方法
- 2019年开发人员应该学习的8个JavaScript框架
- HTML中的script标签研究
- 对一个分号引发的错误研究
- 异步流程控制:7 行代码学会 co 模块
- ES6 走马观花(ECMAScript2015 新特性)
- JavaScript拆分字符串时产生空字符的原因
- Canvas 在高清屏下绘制图片变模糊的解决方法