How to use a crossdomain JSON request using jQuery
First you have to create your client script. We’ll include the jQuery librry and we’ll create a standard ajax request:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$.ajax({
error: function(jqXHR,textStatus,errorThrown){alert(textStatus+' '+errorThrown)},
url: "http://www.yourdomain.com/json.php",
success: function(data){alert(data)},
dataType: 'json',
data: {}
});
</script>
Now you will most likely get the following error:
Origin http://www.yourdomain.com is not allowed by Access-Control-Allow-Origin.
So it’s time to set your server the right way:
If your are using something like this:
<?php
echo json_encode(array('a','r','r','a','y'));
?>
it will not work. You have to specify Access-Control-Allow-Origin access. You can enable it for one site, or you can give access to all websites. Here’s how to do it:
<?php
header('Access-Control-Allow-Origin: *');
echo json_encode(array('a','r','r','a','y'));
?>
and the result is:

Thanks for posting this, I haven’t worked much with jQuery so I’ve been meaning to try out some jQuery examples. This looks like a good one to try out!
Justin Cooney
26 Aug 11 at 21:12