上篇博客介绍了同源策略和跨域访问概念,其中提到跨域常用的基本方式:JSONP和CORS。
http://localhost:11111/user?callback=callbackfunction
则服务器返回的数据如下:
callbackfunction({"id":1,"name":"test"})
JS中:
<script>
var url = "http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=callbackfunction";
var script = document.createElement(‘script‘);
script.setAttribute(‘src‘, url); //load javascript
document.getElementsByTagName(‘head‘)[0].appendChild(script);
//回调函数
function callbackfunction(data){
var html=JSON.stringify(data.RESULTSET);
alert(html);
}
public class TestJson extends ActionSupport{
@Override
public String execute() throws Exception {
try {
JSONObject jsonObject=new JSONObject();
List list=new ArrayList();
for(int i=0;i<4;i++){
Map paramMap=new HashMap();
paramMap.put("bank_no", 100+i);
paramMap.put("money_type", i);
paramMap.put("bank_name", i);
paramMap.put("bank_type", i);
paramMap.put("bank_status", 0);
paramMap.put("en_sign_ways", 1);
list.add(paramMap);
}
JSONArray rows=JSONArray.fromObject(list);
jsonObject.put("RESULTSET", rows);
HttpServletRequest request=ServletActionContext.getRequest();
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/javascript");
boolean jsonP = false;
String cb = request.getParameter("jsonp");
if (cb != null) {
jsonP = true;
System.out.println("jsonp");
response.setContentType("text/javascript");
} else {
System.out.println("json");
response.setContentType("application/x-json");
}
response.setCharacterEncoding("UTF-8");
Writer out = response.getWriter();
if (jsonP) {
out.write(cb + "("+jsonObject.toString()+")");
System.out.println(jsonObject.toString());
}
else{
out.write(jsonObject.toString());
System.out.println(jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
$.ajax({
type:"GET",
async :false,
url:"http://localhost:8080/crcp/rcp/t99eidt/testjson.do",
dataType:"jsonp",
success:function(data){
var html=JSON.stringify(data.RESULTSET);
$("#testjsonp").html(html);
},
error:function(){
alert("error");
}
});
http://www.w3school.com.cn/jquery/ajax_ajax.asp
jsonp:jsonp,则请求的地址为:http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=自动生成回调函数名
jsonpCallback:callbackfunction,则请求的地址为:
http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=callbackfunction
最后返回前台的是:
callbackfunction(具体的json值)
本文转载自:http://blog.csdn.net/yuebinghaoyuan/article/details/32706277
原文:http://www.cnblogs.com/MonaSong/p/5340354.html