Sunday, April 3, 2011

A question about cross-domain (subdomain) ajax request.

Let's say I have the main page loaded from http://www.example.com/index.html. On that page there is js code that makes an ajax request to http://n1.example.com//echo?message=hello. When the response is received a div on the main page is updated with the response body.

Will that work on all popular browsers?

Edit:

The obvious solution is to put a proxy in front of www.example.com and n1.example.com and set it so that every request going to a subresource of http://www.example.com/n1 gets proxied to http://n1.example.com/.

From stackoverflow
  • Probably not. These are two different domain names so cross-domain request thus blocked by browsers.

  • Another solution that may or may not work for you is to dynamically insert/remove script tags in your DOM that point to the target domain. This will work if the target returns json and supports a callback.

    Function to handle the result:

    <script type="text/javascript">
      function foo(result) {
        alert( result );
      }
    </script>
    

    Instead of doing an AJAX request you would dynamically insert something like this:

    <script type="text/javascript" src="http://n1.example.com/echo?callback=foo"></script>
    
    johnnietheblack : thats an interesting way to go about it...cool
    Justice : This technique is known as JSONP. The major JavaScript frameworks have this capability in their AJAX libraries.
    David Underhill : Great workaround!
  • Another workaround, is to direct the ajax request to a php (for example) page on your domain, and in that page make a cURL request to the subdomain.

  • Cross domain is entirely a different subject. But cross sub-domain is relatively easy.

    More info here: http://www.tomhoppe.com/index.php/2008/03/cross-sub-domain-javascript-ajax-iframe-etc/

    Jordan : Too bad another "correct" answer has been chosen that isn't. This is the correct answer to the question. Domains that share a second-level domain (with some small exceptions) can always set their domain to allow broader access amongst other domains that share the subdomain.
  • I faced the same problem during 2 days and I found the solution, and it's elegant after googling a lot. I needed xss Ajax for some widget clients which pull datastream from tiers websites to my Rails app. here's how I did.

    Will : Appreciate the answers, but just linking people to your blog is going to do you more harm than good, as people here are pretty sensitive to self-promotion and will end up downvoting and flagging you for spam.

0 comments:

Post a Comment