[java] ajax跨域请求demo

情景

本篇文章,只是简单记录一个ajax跨域请求的demo。
具体关于ajax跨域请求的介绍及原理,可自行Google。

demo
[1].项目介绍

website项目:一个纯前端页面展示的项目
op项目:后端,对前端访问的接口,放开权限。

需求website 中请求op项目中的接口,并获得返回的数据在页面上展示。

清单一:website中ajax 跨域请求
 $(function () {
        getCarouselMap()
    })
 
function getCarouselMap() {
        var postUrl = _host + "/op/webSite/list";
        // var postUrl =  "http://localhost:9003/webSite/list";
        $.ajax({
            type: "get",
            url: postUrl,
            dataType: "jsonp",
            async: false,
            cache: false,
            jsonp: "callbackparam",
            jsonpCallback: "jsonpCallback",
            success: function (result) {
                for (var i = 0; i < result.data.length; i++) {
                     var img_url = result.data[i].imgMiddle
                
                     console.info("图片地址:"+img_url )
                     }
                }
               
            },
            error: function (result) {
            }
        });


清单二:op中/webSite/list 接口

特别注意:调用op中的项目,如果涉及到权限,需要将该接口的权限打开。
最好添加上,response.setContentType("text/javascript;charset=UTF-8");
如果不添加,如果你使用的服务器框架较新,chrome浏览器无法解析。
chrome浏览器会报错:Refused to execute script from 'http://localhost:9003/webSite/list?callbackparam=jsonpCallback&apply
chrome浏览器报错:

Refused to execute script from 'xxxxxxxxxx' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.

报错原因:

因为服务器端框架比较新,在响应头文件中加了如下参数,
可以在浏览器调试器的网络中查看到:
x-content-type-options:nosniff
而chrome只能访问响应内容类型为如下的JSONP接口:

   "application/ecmascript"
    "application/javascript"
    "application/x-javascript"
    "text/ecmascript"
    "text/javascript"
    "text/jscript"
    "text/x-javascript"
    "text/vbs"
    "text/vbscript"

op中/webSite/list 接口
class WebSiteController {
  CarouselMapService carouselMapService
   // web-site portal 轮播图
    def list() {
        ApiRest apiRest=new ApiRest();
        String callBack=params["callbackparam"]
        try {
            apiRest=carouselMapService.websiteOfList()
            response.setContentType("text/javascript;charset=UTF-8");//如果不这样设置 chrome浏览器无法调用
        } catch (Exception e) {
            apiRest.error=e.message
            apiRest.isSuccess=false
            LogUtil.logError(e.message,params,"saveInfo"+e.message)
        }
        render callBack + "("+ (apiRest as JSON) +")";
    }

}


参考链接:

1.解决chrome浏览器跨域请求报Refused to execute script from
2.解决ajax跨域问题【5种解决方案】
3.AJAX跨域调用相关知识-CORS和JSONP(引)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值