现在有需求是这样的:
项目前后端分离,分别使用不同的服务器,前端使用ajax访问后端的方法时出现了跨域问题,以下是解决方法
前端:
$.ajax({
type : "get",
async:false,
url : "",
dataType : "jsonp",//数据类型为jsonp
jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data){
$("#showcontent").text("Result:"+data.result)
},
error:function(){
alert('fail');
}
});
后端---原来的方式(json)
net.sf.json.JSONArray jsonArray = null;
try {
jsonArray = net.sf.json.JSONArray.fromObject(treeList);
} catch (Exception e) {
e.printStackTrace();
}
if (jsonArray != null) {
PrintWriter writer = response.getWriter();
writer.print(jsonArray);
}
现在的后端(jsonP)
if (jsonArray != null) {
json2jsonP(response, request, jsonArray);
PrintWriter out = response.getWriter();
String jsonpCallback = request.getParameter("callback");//客户端请求参数
out.println(jsonpCallback+"("+jsonArray.toString()+")");//返回jsonp格式数据
out.flush();
out.close();
}