简体   繁体   中英

Making AJAX calls from subdomain to main domain with relative paths

I have the following structure: http://subdomain.mysite.com

From there, I want to be able to make an AJAX call to: http://mysite.com/releases/ajax/file.php

If I use the absolute URL like above, JS gives an error that states "permissions error" on line:

xmlhttp.open("POST",url,true);

Is there a way to get there with relative paths from the subdomain? If not, I would probably put a redirect to use mysite.com/subdomains .

This is because of the Same Origin policy. AJAX requests by default cannot cross domain boundaries, even if it's a subdomain (even for mysite.com and www.mysite.com, or https://mysite.com and http://mysite.com ). You can find out a little more about this security feature here:
http://en.wikipedia.org/wiki/Same_origin_policy

Because this restrictive limitation is so problematic for developers, newer browsers support a policy framework called CORS (Cross-Origin Resource Sharing), which allows you to specify allowed hosts to communicate with. Unfortunately, basic support wasn't implemented into Internet Explorer until version 8, so if you have to support IE6-7, it won't work for you:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

What most people will do in this situation is to use JSONP instead, which takes advantage of the fact that normal script tags aren't bound by the Same Origin policy, and so the JSON response is wrapped in a function call and executed by the browser, allowing that callback access to that data. More info on JSONP:
http://en.wikipedia.org/wiki/JSONP

One notable limitation of JSONP is that it can only be used for GET requests to the server (not POST or other HTTP request types).

Many popular JavaScript frameworks, such as jQuery, support JSONP as an option (most just by switching a request type variable when creating the AJAX request), but obviously you also still need to set up the server-side script that is handling these requests to respond appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM