跨域说明
跨域指请求和服务的域不一致,浏览器和h5的ajax请求有影响,而对服务端之间的http请求没有限制。
跨域是浏览器拦截了服务器端返回的相应,不是拦截了请求。
jsonp跨域请求处理
jsonp(json with padding) 是 json的一种"使用模式",可以让网页从别的域名(网站)那获取资料,绕过同源策略(若地址里面的协议、域名和端口号均相同则属于同源),即跨域读取数据。
jsonp:利用script标签可以跨域,让服务器端返回可执行的javascript函数,参数为要回发的数据。可看做带有回调函数的ajax请求。
js代码
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<script type= "text/javascript" >
$(function(){
/*
//简写形式,效果相同
$.getjson("http://app.example.com/base/json.do?sid=1494&busiid=101&jsonpcallback=?",
function(data){
$("#showcontent").text("result:"+data.result)
});
*/
$.ajax({
type : "get" ,
async: false ,
url : "http:/xxx" ,
datatype : "jsonp" , //数据类型为jsonp
jsonp: "jsonpcallback" , //服务端用于接收callback调用的function名的参数
jsonpcallback: "自定义回调函数名"
success : function(data){
alert(data.info)
},
error:function(){
alert( 'fail' );
}
});
});
</script>
|
java后端处理代码
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@responsebody
@requestmapping (value = "/url" , produces= mediatype.application_json)
public string test(
httpservletrequest request,
httpservletresponse response) throws exception{
string result = getresult();
response.setheader( "pragma" , "no-cache" );
response.setheader( "cache-control" , "private,no-cache,no-store,max-age=0" );
response.setdateheader( "expires" , 0 );
string str=request.getparameter( "jsonpcallback" );
if (str== null ||str.equals( "" )) {
return result;
} else {
return str + "(" + result + ")" ;
}
}
|
cors(协议跨域资源共享)(cross-origin resource sharing)
它允许浏览器向跨源服务器,发出xmlhttprequest请求,从而克服了ajax只能同源使用的限制 详细介绍
- access-control-allow-origin:* 允许所有域名的脚本访问该资源
- access-control-allow-methods:get,post,put,delete,options 运行什么方式访问资源
- access-control-expose-headers:x-requested-with 暴露的信息
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。
原文链接:http://www.cnblogs.com/chenzd/p/9989682.html
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
网站服务器关闭解决方案与临时维护指南:数据迁移及应急处理优化
2025-05-25 91 -
2025-05-27 88
-
2025-05-29 80
-
2025-05-27 37
-
2025-05-29 22
热门评论