ajax跨域访问后台有两种解决方式,一种是在页面中添加标记的方法,这种方法区别浏览器,所以如果考虑兼容性的话,不建议使用。我列出来的是利用代码解决跨域的问题。重点是“jsonp”、“jsonpCallback”。有疑问或者更好的方法欢迎留言
$.ajax({
url:"http://localhost:8080/KLCoin/informationAction!addInformation.action",type:"post",//请求方式
async : false,//同步:true:同步;false:异步
cache : false,//缓存
dataType : "jsonp",//跨域访问的重点,设置jsonp
jsonp: "jsonpCallback",//回调函数
data:data,//传递给后台的书
success:function(result){
//result为后台返回结果
},
error:function(){
console.info("error=========");
}
});
(1)jsonp的作用是设置服务器获取回调函数名称参数的下标参数,
jsonpCallback的作用就是设置回调函数,相当于input标签中name和value,
jsonp对应name,value对应jsonpCallback。
(2)ajax和jsonp其实本质上是不同的东西。ajax的核心是通过XmlHttpRequest获取非本页内容,
而jsonp的核心则是动态添加<script>标签来调用服务器提供的js脚本。
后台接收数据方法
public void addInformation() {
// 解决跨域问题
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/plain");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setCharacterEncoding("UTF-8");
InformationVo information = new InformationVo();
information.setSname(request.getParameter("sname"));
information.setScompany(request.getParameter("scompany"));
information.setSphone(request.getParameter("sphone"));
information.setIwechar(request.getParameter("iwechar"));
String stitle = request.getParameter("stitle");
if (!("").equals(stitle)) {
information.setStitle(stitle);
}
String scontent = request.getParameter("scontent");
if (!("").equals(scontent)) {
information.setScontent(scontent);
}
Result result = informationService.saveInfo(information);
Map<String, String> map = new HashMap<String, String>();
map.put("result", result.getDescription());
PrintWriter out = null;
try {
out = getResponse().getWriter();
String jsonString = map.toString();
String jsonpCallback = request.getParameter("jsonpCallback");// 客户端请求参数
out.print(jsonpCallback + "(" + jsonString + ")");//前台result的值
} catch (IOException e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
}
}