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为后台返回结果
console.info(“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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/158208.html