解决Ajax跨域访问后台的问题

得意时要看淡,失意时要看开。不论得意失意,切莫大意;不论成功失败,切莫止步。志得意满时,需要的是淡然,给自己留一条退路;失意落魄时,需要的是泰然,给自己觅一条出路解决Ajax跨域访问后台的问题,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

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

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!