情景
本篇文章,只是简单记录一个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(引)