最近用JQueryMoblie嵌入项目的appl里涉及到Ajax异步刷新listView,最初的代码是:
$.ajax({
url : url,
type : "POST",
data : JSON.stringify(ajax_data),
dataType : "json",// 返回数据为json
contentType : "application/json;charset=UTF-8",
success:function(m){
alert(m);
}
})
但是不幸的是……出现了这种错误:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
百度了一下 说是这是跨域造成的。
知道哪里错了 就开始改进吧,用的是Ajax自带的jsonp解决的跨域问题:
$.ajax({
url : url,
type : "POST",
data : JSON.stringify(ajax_data),
dataType : "jsonp",// 返回数据为jsonp
contentType : "application/json;charset=UTF-8",
jsonp : "callbackparam",
jsonpCallback : "success_jsonpCallback",
success:function(m){
alert(m);
}
})
1、这里面的type类型是POST,但是jsonp用的是GET 应该是Ajax设定的,所以后台接受的时候也要是GET模式接受
2、dataType : "jsonp" jsonp设置的传回来的类型必须是jsonp
3、jsonp : "callbackparam" 和 jsonpCallback : "success_jsonpCallback" 这个使用jsonp的固定格式,必须添加的(参数随意),后台也要根据jsonp格式对json字符串做下改动
4、后台。我用的是Spring-MVC,为了实现效果,先试用最简单的方法,代码如下:
@RequestMapping(value = "/sale/getWebList", method = RequestMethod.GET)
public void getSaleList(HttpServletRequest request, HttpServletResponse response) throws IOException {
String callBack = request.getParameter("callbackparam");//此时得到的callback 就是前台设置的success_jsonpCallback,用于后面对json的处理
String prefType = null;
String card = null;
String city = null;
String mcType = null;
String pageSize = null;
String pageNum = null;
try {
prefType = java.net.URLDecoder.decode(request.getParameter("prefType"), "UTF-8");
card = java.net.URLDecoder.decode(request.getParameter("card"), "UTF-8");
city = java.net.URLDecoder.decode(request.getParameter("city"), "UTF-8");
mcType = java.net.URLDecoder.decode(request.getParameter("mcType"), "UTF-8");
pageSize = request.getParameter("pageSize");
pageNum = request.getParameter("pageNum");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} finally {
log.info(request.toString());
}
List<SaleInfo> saleList = saleSearchService.getSaleList(prefType, card, city, mcType, pageNum, pageSize);
Gson gson = new Gson();
String saleGson = gson.toJson(saleList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(callBack + "(" + saleGson + ")");//研究了json和jsonp的区别之后,发现jsonp就是在json的外围用callback加了一层封装,然后传给前台
}
因为这个项目从前台传递过来的参数可能包含中文,为了解决中文乱码问题,需要在前台的参数上面进行编码操作:"prefType" : encodeURI(v_prefType)
然后后台接收的时候对字符串进行解码操作:prefType = java.net.URLDecoder.decode(request.getParameter("prefType"), "UTF-8");