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

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();
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值