java web支持jsonp的实现代码

2025-05-29 0 48

跨域说明

跨域指请求和服务的域不一致,浏览器和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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 java web支持jsonp的实现代码 https://www.kuaiidc.com/110768.html

相关文章

发表评论
暂无评论