jQuery AJAX cross domain jQuery AJAX cross domain ajax ajax

jQuery AJAX cross domain


Use JSONP.

jQuery:

$.ajax({     url:"testserver.php",     dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)     success:function(json){         // do stuff with json (in this case an array)         alert("Success");     },     error:function(){         alert("Error");     }      });

PHP:

<?php$arr = array("element1","element2",array("element31","element32"));$arr['name'] = "response";echo $_GET['callback']."(".json_encode($arr).");";?>

The echo might be wrong, it's been a while since I've used php. In any case you need to output callbackName('jsonString') notice the quotes. jQuery will pass it's own callback name, so you need to get that from the GET params.

And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?' to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).


JSONP is a good option, but there is an easier way. You can simply set the Access-Control-Allow-Origin header on your server. Setting it to * will accept cross-domain AJAX requests from any domain. (https://developer.mozilla.org/en/http_access_control)

The method to do this will vary from language to language, of course. Here it is in Rails:

class HelloController < ApplicationController  def say_hello    headers['Access-Control-Allow-Origin'] = "*"    render text: "hello!"  endend

In this example, the say_hello action will accept AJAX requests from any domain and return a response of "hello!".

Here is an example of the headers it might return:

HTTP/1.1 200 OK Access-Control-Allow-Origin: *Cache-Control: no-cache, no-store, max-age=0, must-revalidateContent-Type: text/html; charset=utf-8X-Ua-Compatible: IE=EdgeEtag: "c4ca4238a0b923820dcc509a6f75849b"X-Runtime: 0.913606Content-Length: 6Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)Date: Thu, 01 Mar 2012 20:44:28 GMTConnection: Keep-Alive

Easy as it is, it does have some browser limitations. See http://caniuse.com/#feat=cors.


You can control this via HTTP header by adding Access-Control-Allow-Origin. Setting it to * will accept cross-domain AJAX requests from any domain.

Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain:

header("Access-Control-Allow-Origin: *");

Don't forget to enable mod_headers module in httpd.conf.