A few days ago i posted an article about making a JSON request using $.getJSON().
jQuery & JSON – Make JSON GET request using jQuery.getJSON()
But i have made a mistake there because i didn’t realize the Cross Domain problem. So this article shows you how to resolve the Cross Domain issue in $.getJSON() by JSONP.
1. Modify the server.php as follow.
<?php $arr1 = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); $arr2 = array ('a'=>5,'b'=>4,'c'=>3,'d'=>2,'e'=>1); if ($_GET['param1'] == 'ykyuen' && $_GET['param2'] == 'eureka') { // Instead of printing the json object directy, we wrap it with the request // callback name which is jsonp in this example print $_GET['jsonp'].'('.json_encode($arr1).')'; } else { print $_GET['jsonp'].'('.json_encode($arr2).')'; } ?>
2. Add the append the callback name in the request URL in the json-get.php
<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> </head> <body> <script> // Append "?jsonp=?" to the request URL $.getJSON('http://<other-domain>/server.php?jsonp=?', { param1: "ykyuen", param2: "eureka" }, success ); function success(data) { $.each(data, function(key, val) { $("body").append(key + " : " + val + "<br/>"); }); } </script> </body> </html>
You can name the callback arbitrarily.
Done =)
Reference: StackOverflow – “invalid label” Firebug error with jQuery getJSON
Advertisements
3 thoughts on “jQuery & JSON – Make Cross Domain Request Using jQuery.getJSON() with JSONP”