<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);
}
</script>
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;
}
}
$(function(){
jQuery.getJSON("http://localhost:8080/crcp/rcp/t99eidt/testjson.do?jsonp=?",function(data)
{
var html=JSON.stringify(data.RESULTSET);
$("#testjsonp").html(html);
}
);
});
$.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");
}
});
跨域JSONP原理及调用具体示例,布布扣,bubuko.com
原文:http://blog.csdn.net/yuebinghaoyuan/article/details/32706277