Jquery实现跨域(具体通过jsonp格式)请求返回数据,即A应用访问B应用的某一个Action需要得到某个数据,那么A端通过Ajax请求B的具体方法,实现如下:
A端 js:
$().ready(function(){ $.ajax({ type: "post", url:"http://192.168.20.78:8080/eventAction_toDoEventCount.action?userId=+"+userId+"+&time="+doTime+"", dataType:"jsonp", jsonp:"callback", success: function(count){ $('#waitHandleEvent').text(count); } }); }
Success回调的函数中的参数count既是返回的结果(去除jsonp标志串的结果)
B端java代码:
String jsonp =this.getRequest().getParameter("callback");//必要的,他是jsonp自动转化的标志串,返回数据时需要其做解析
HttpServletResponseresponse=this.getResponse();
PrintWriterout=null;
try {
String jsonpMessage = jsonp +"(" +message+")";
out=response.getWriter();
out.write(jsonpMessage);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}finally{
if(out!=null){
out.close();
}
}