如何进行跨域请求 [英] How to make cross domain request

查看:142
本文介绍了如何进行跨域请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如你所知,网络浏览器的安全性不允许创建跨域请求。我读了一本书,说,你应该使用XMLHTTPRequest只有当你可以把文件放在服务器上(意味着将页面加载到同一个请求的域)。



$ b

b


  1. 什么是XMLHTTPRequest的跨域替代?

  2. WebSockets 此技术是否允许跨域请求?

EDIT:
仍然不清楚给我...



例如,我从 www.domain1.com 拉我的页面,我需要从 www.domain2.com 。因此,被拉取的页面应该包括:

 < script src =www.domain2.com/script.js> ;< / script> 

以避免跨域限制。



我可以使用JSONP,请求将如下所示:
http://ww.domain1。 com /?callback = someFunction.js



但是:不一样。我只是从另一个领域拉js!

解决方案

您可以使用 XMLHttpRequest 对象。这是使用称为跨源资源共享的东西。请参阅:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing



很简单,当请求发送到服务器时,服务器可以用 Access-Control-Allow-Origin 头部将允许或拒绝请求。浏览器需要检查这个头,如果允许,它将继续请求过程。如果没有,浏览器将取消请求。



您可以在这里找到更多信息和一个工作示例:
http://www.leggetter.co.uk/2010/03/ 12 / making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html



JSONP是另一种解决方案,它有点黑客。


As you know, the security of the web browser disallows the making of cross domain requests. I read a book which says that you should use XMLHTTPRequest only if you can put the files on the server (means put the page you will load to the same requested domain). If you can't - you should search for an alternative.

My questions are:

  1. What is the cross domain alternative to XMLHTTPRequest?
  2. What about WebSockets? Does this technology allow cross domain request?

EDIT: It still isn't clear to me...

For example, I pull my page from www.domain1.com and I need to request javascript from www.domain2.com. So the pulled page should include something like:

<script src="www.domain2.com/script.js"></script>

to avoid cross domain restrictions.

And I can use JSONP, and request will look like: http://ww.domain1.com/?callback=someFunction.js

But: isn't it the same. I just pull js from the another domain! Do it avoid cross domain restrictions?

解决方案

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

这篇关于如何进行跨域请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆