前面作了一個demo實現ssl證書認證,實現後再跑整個項目流程時發現,有些鏈接、返回值沒法正常鏈接與傳遞。ajax
這時,就涉及到了跨域問題。json
因此要進行一些改動跨域
1、前臺AJAX訪問app
var sign_url=basepath+"/user/login.do";async
修改前的ajax:函數
$.ajax({
url: sign_url,
data: {loginName:username,pwd:password},
dataType: 'json',
type: 'post',
async: true,
success: function (data) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});post
修改後的ajax:jsonp
$.ajax({
url: sign_url+"?loginName="+username +"&pwd="+password,
dataType: 'jsonp',
type: 'post',
async: true,
jsonp: "callback",//傳遞給請求處理程序或頁面的,用以得到jsonp回調函數名的參數名(通常默認爲:callback)
jsonpCallback:"flightHandler",//自定義的jsonp回調函數名稱,默認爲jQuery自動生成的隨機函數名,也能夠寫"?",jQuery會自動爲你處理數據
success: function (data) {
alert("success");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});url
2、後臺返回orm
修改前的後臺返回:
public static void write(final HttpServletResponse response, final Object obj1, final String datePattern) {
if(obj1==null) return;
Object obj = obj1;
PrintWriter out = null;
try {
JsonConfig cfg = new JsonConfig();
registerConf(cfg);
if(obj1 instanceof Pagination<?>) obj = JSONObject.fromObject(obj1,cfg);
dformat.applyPattern(datePattern);
Object json = null;
defaultNull(obj);
if(obj instanceof List||(obj instanceof String && obj.toString().startsWith("[") && obj.toString().endsWith("]"))){
json = JSONArray.fromObject(obj,cfg);
}else{
json = JSONObject.fromObject(obj,cfg);
}
out = response.getWriter();
out.print(json);
} catch (IOException e) {
LOG.error("輸出流獲取異常[obj]"+obj.toString(), e);
} finally {
if(out!=null) out.close();
}
}
修改後的後臺:
public static void writeByCallback(final HttpServletResponse response, final Object obj1, final String datePattern, final HttpServletRequest request) {
if(obj1==null) return;
Object obj = obj1;
PrintWriter out = null;
try {
JsonConfig cfg = new JsonConfig();
registerConf(cfg);
if(obj1 instanceof Pagination<?>) obj = JSONObject.fromObject(obj1,cfg);
dformat.applyPattern(datePattern);
Object json = null;
defaultNull(obj);
if(obj instanceof List||(obj instanceof String && obj.toString().startsWith("[") && obj.toString().endsWith("]"))){
json = JSONArray.fromObject(obj,cfg);
}else{
json = JSONObject.fromObject(obj,cfg);
}
out = response.getWriter();
out.println(request.getParameter("callback")+"("+json.toString()+")");//返回jsonp格式數據
} catch (IOException e) {
LOG.error("輸出流獲取異常[obj]"+obj.toString(), e);
} finally {
if(out!=null) out.close();
}
}
添加了final HttpServletRequest request,經過request獲取callback(即:request.getParameter("callback")),前臺ajax傳過來的jsonp