浙江省高等学校教师教育理论培训

微信搜索“毛凌志岗前心得”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

How To Do A JavaScript Cross-Domain POST or GET With jQuery or XMLHttpRequest | Websitez.com

16

How To Do A JavaScript Cross-Domain POST or GET With jQuery or XMLHttpRequest

Posted by Eric Stolz in How To, jQuery

 

If you have spent any significant amount of time in JavaScript sending data to the server, you have probably come across the strict cross-domain policy that has been in existence since the beginning of AJAX.

There are ways around this such as a proxy script, but they are all kind of a pain. Most people are unaware of the fact that it is possible to create a JavaScript POST cross-domain, and it is fairly easy to do. It is true that not all browsers support this, but you will be pleasantly surprised to know that the following browsers do support it: Internet Explorer 8+, Firefox 3.5+, Safari 4+, and Chrome. Yes, IE8+ does support it. I was surprised too.

So the big question is, how does it work? Cross-domain ajax is achieved through a protocol called Cross-Origin Resource Sharing.

Cross-Origin Resource Sharing

Cross-Origin Resource Sharing is a W3C Working Draft that defines how the browser and server must communicate when accessing sources across origins. The basic gist is that the client and server use special headers to either deny or accept a cross-origin request.

For example, if a script such as http://www.websitez.com/list.js performs a POST request via AJAX to the website http://www.hosting.com/save_listings.php, it would normally fail due to cross-origin policy. However, if in the PHP script “save_listings.php”, you set a special header called “Access-Control-Allow-Origin” with the proper value, the POST will be successful.

In PHP, the proper code for the “save_listings.php” file would be:

header(“Access-Control-Allow-Origin: http://www.websitez.com”);

By setting that header value, it will allow the script located at http://www.websitez.com/list.js to perform POST and GET requests cross-origin to the http://www.hosting.com/save_listings.php script, which is on an entirely different domain.

There are additional headers that can be set as well:

Access-Control-Allow-Origin: http://www.websitez.com
Access-Control-Allow-Methods: POST, GET
Access-Control-Allow-Headers: NCZ
Access-Control-Max-Age: 1728000

You can also specify a “*” as the domain to allow any domain to perform a POST or GET to the script in question. Obviously this is a massive security risk and should only be done if you know the exact ramifications of doing so.

Access-Control-Allow-Origin: *

For further information, please checkout this great post from NCZOnline detailing the proper way to perform the AJAX call to maximize support across as many browsers as possible as well as further details on the additional headers that you can specify to gain control over who, when, and what can access your script.

posted on 2012-05-09 17:30  lexus  阅读(662)  评论(0编辑  收藏  举报