对于想了解ajax跨域请求的读者,本文将提供新的信息,我们将详细介绍ajax跨域请求api,并且为您提供关于ajax---Ajax跨域请求保证同一个session的问题、ajax---解决ajax跨域
对于想了解ajax 跨域请求的读者,本文将提供新的信息,我们将详细介绍ajax 跨域请求api,并且为您提供关于ajax --- Ajax 跨域请求保证同一个 session 的问题、ajax --- 解决ajax跨域请求导致session失效的问题、ajax 跨域请求处理、ajax 跨域请求问题的有价值信息。
本文目录一览:- ajax 跨域请求(ajax 跨域请求api)
- ajax --- Ajax 跨域请求保证同一个 session 的问题
- ajax --- 解决ajax跨域请求导致session失效的问题
- ajax 跨域请求处理
- ajax 跨域请求问题
ajax 跨域请求(ajax 跨域请求api)
问题:
今天开发新东西,需要本地 ajax 请求远程服务器的接口,然后出现了
“ XMLHttpRequestcannotloadhttp://服务器的接口地址?参数.No'Access-Control-Allow-Origin'headerispresentontherequestedresource.Origin'http://localhost:8080'isthereforenotallowedaccess.”
这个错误,但是请求本地项目的接口就没有问题。上网搜索了一下,得到如下结果
原因:
ajax不能跨域访问,所以本地请求接口没有问题(同样都是localhost),而请求服务器端就不可以了(一个是localhost,一个是远程服务器)
解决办法:
在ajax 的请求接口页面加上 代码
response.addheader("Access-Control-Allow-Origin","*");
response 为HttpServletResponse 类型,我是jsp开发。
ajax --- Ajax 跨域请求保证同一个 session 的问题
我们知道,根据浏览器的保护规则,跨域的时候我们创建的 sessionId 是不会被浏览器保存下来的,这样,当我们在进行跨域访问的时候,我们的 sessionId 就不会被保存下来,也就是说,每一次的请求,服务器就会以为是一个新的人,而不是同一个人,为了解决这样的办法,下面这种方法可以解决这种跨域的办法。
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) servletResponse;
HttpServletRequest request=(HttpServletRequest)servletRequest;
res.setContentType("textml;charset=UTF-8");
res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
res.setHeader("Access-Control-Max-Age", "0");
res.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("XDomainRequestAllowed","1");
filterChain.doFilter(servletRequest,servletResponse);
}
在 ajax 请求是也要加相应的东西
$.ajax({
url:url,
//加上这句话
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function(result){
alert("test");
},
error:function(){
}
});
这样我们再跨域测试的时候,就会发现我们的 sessionId 是一样的了,这样就实现了跨域并且保证在同一个 session 下。
ajax --- 解决ajax跨域请求导致session失效的问题
起因:http是无状态的,因此我们通常需要用到cookie以及session来保存状态,session是在服务器端存储的,会和cookie一起使用,设置了session之后,会发送给浏览器一个cookie,这个cookie是session_id,当再次请求的时候浏览器会将它发送给服务器,以此来找到对应的session.
但是,我们实际使用的时候通常会用到跨域,就是向不同的域发起请求,但是默认情况下此时cookie是不会发送给服务器的,此时就导致了丢失session_id,从而导致了session的值为undefined。解决方案如下:
首先,前端页面发起ajax请求时,加上参数:
withCredentials: true,
像这样
$.ajax({
type:
url:''http://localhost:8080/user-login'',
data:
dataType:''JSON'',//注意哦,这一句要记得加上哦,我就是因为没加这句还查了好久的
withCredentials: true,
success:
error:
})
我使用的后台语言是node.js,在node.js中使用cors跨域
在app.js中加上(注意接口的顺序哦):
app.all(''*'', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "这里填可以跨域访问的域,不能填*哦");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",'' 3.2.1'');
res.header("Access-Control-Allow-Credentials",true);
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
ok,和bug一站到底,加油
ajax 跨域请求处理
我们主要是采用json传输数据的方式处理
JSONP(JSON with Padding)是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <Meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <Meta http-equiv="refresh" content="url=https://www.serve888.com/serve888/chatClient/chatBox.jsp?companyID=217"> <title>服务中心</title> <style> html,body{margin:0;padding:0;} </style> <script type="text/javascript" src="scripts/jquery.js"></script> </head> <body> <script language="javascript" type="text/javascript"> $(function(){ var url = "http://program/test/test.PHP?username=laobi&jsoncallback=?"; $.ajax({ url: url,type: 'GET',dataType: 'json',//timeout: 1,success: function(data){ alert(data.status); } }); }); </script> </body> </html>
test.PHP
$arr = array('username'=>trim($_GET['username']),'status'=>'1'); echo trim($_GET['jsoncallback']).'('.json_encode($arr).')';
输出
ajax 跨域请求问题
JQuery1.2后getJSON方法支持跨域读取json数据,原理是利用一个叫做jsonp的概念。当然,究其本质还是通过script标签动态加载js,似乎这是实现真正跨域的唯一方法。
getJSON的用法JQuery手册已经写得很详细,参考手册就可以了,很简单。需要指出的一点是getJSON利用的jsonp需要客户端与服务端作出配合。
- 客户端传递的URL里要包含callback变量,以形如callback=?的形式结尾。(jquery会随机生成一个字符串替换?传递给服务端)
- 服务端获取客户端传递的callback的值callbackValue,和需要传递的json字符串构成 callbackValue.’(’.json.’)'传回给客户端(示例为PHP字符串连接方式,其他语言类似)
不出意外的话应该已经可以跨域读取了。
同时输出json数据时候{之前的是(
的中,由于安全的问题,浏览器默认是不支持跨域调用的。传统的方法,包括:(参考http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/)
Local proxy:Needs infrastructure (can't run a serverless client) and you get double-taxed on bandwidth and latency (remote - proxy - client).Flash:Remote host needs to deploy a crossdomain.xml file,Flash is relatively proprietary and opaque to use,requires learning a one-off moving target programming langage.Script tag:Difficult to kNow when the content is available,no standard methodology,can be considered a "security risk".以上方法都各有缺陷,都不是很好多解决方案。后来出现了一种叫JSON with Padding的技术,简称JSONP.(原理参考http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/),应 用JSONP可以实现JSON数据的跨域调用。非常的幸运,JQuery1.2以后支持JSONP的应用。下面侧重说明在JQuery中,Json的跨域调用。
应用JSONP实现Json数据跨域调用,需要端与客户端的合作完成。引用Jquery官方的例子,客户端掉用如下:
1 |
$.getJSON( " http://api.flickr.com/services/Feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=? " , |
2 | function (data){ |
3 | $.each(data.items,(i,item){ |
"<img/>"
).attr(
"src"
);
5 | if( i == 3 ) return false ; |
7 | }); |
注意这里调用的地址中jsoncallback=?是关键的所在!其中,符号会被Query自动替换成其他的回调方法的名称,具体过程和原理我们这里不理 会。我们关心的是jsoncallback=?起什么作用了?原来jsoncallback=?被替换后,会把方法名称传给服务器。我们在服务器端要做什 么工作呢?服务器要接受参数jsoncallback,然后把jsoncallback的值作为JSON数据方法名称返回,比如服务器是,我们会这 样做:
...
String jsoncallback=request.getParameter("jsoncallback");
out.print(jsoncallback+"({\"account\":\"XX\",\"passed\":\"true\",\"error\":\"null\"})");
Jquery取得的可能如下:
JQUET0988788({"account":"XX","passed":"true","":"null"})
总结,用JSONP要做两件事:
1/请求地址加参数:jsoncallback=?
2/服务器段把jsoncallback的值作为方法名传回来,如JQUET098788(...)
jQuery从1.2开始就支持XMLHttp跨域请求了,具体怎么操作?
jQuery中跨域访问的核心原理:JS文件注入,因为因为script标签的src属性是可以跨域的,利用script标签的src属性直接返回非本域名下的数据,具体采用的方式称为:jsonp。
代码:
test.html,例如位于www.qq.com
01 | <!DOCTYPE html PUBLIC "-//W3C//DTD 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> |
html
xmlns
=
"http://www.w3.org/1999/xhtml"
>
03 | head> |
http-equiv
"Content-Type"
content
"text/html; charset=gb2312"
/>
05 | title>jQuery-跨域请求</ 06 |
scripttype "text/javascript" src "/js/jquery.js" ></ script 07 |
</08 |
"text/javascript" 09 |
jQuery(document).ready(function(){ |
11 | type : "GET",monospace!important; border:0px!important; outline:0px!important; text-align:right!important; float:none!important; vertical-align:baseline!important; position:static!important; left:auto!important; top:auto!important; right:auto!important; bottom:auto!important; height:auto!important; width:2.7em!important; line-height:1.1em!important; font-size:10pt!important; min-height:inherit!important; display:block!important">12 | url : "http://www.b.com/server.PHP&action=getmsg&callback=?", |
13 | dataType : "jsonp",monospace!important; border:0px!important; outline:0px!important; text-align:right!important; float:none!important; vertical-align:baseline!important; position:static!important; left:auto!important; top:auto!important; right:auto!important; bottom:auto!important; height:auto!important; width:2.7em!important; line-height:1.1em!important; font-size:10pt!important; min-height:inherit!important; display:block!important">14 | jsonp: 'callback',monospace!important; border:0px!important; outline:0px!important; text-align:right!important; float:none!important; vertical-align:baseline!important; position:static!important; left:auto!important; top:auto!important; right:auto!important; bottom:auto!important; height:auto!important; width:2.7em!important; line-height:1.1em!important; font-size:10pt!important; min-height:inherit!important; display:block!important">15 | success : function(json){ |
17 | return true; |
19 | }); |
23
divid
"msg_Box"
div
24
25
html>
server.PHP,例如位于 www.baidu.com
$action
=
$_GET
[
'action'
];
$callback[callback ]; |
() |
echo "{$callback}({" msg ":" this is a jquery jsonp test message! "})" exit (); |
} |
{ |
;
(); |
关于ajax 跨域请求和ajax 跨域请求api的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于ajax --- Ajax 跨域请求保证同一个 session 的问题、ajax --- 解决ajax跨域请求导致session失效的问题、ajax 跨域请求处理、ajax 跨域请求问题等相关知识的信息别忘了在本站进行查找喔。
本文标签: