Tuesday, 5 February 2013

CORS - Cross Domain Resource Sharing With Ajax and JSON - Example

Recently, I was ask to build a prototype to demonstrate cross-domain resource sharing through AJAX and JSON.  For those who dont know, cross-domain AJAX request are not allowed by default until the web server handling the request allows it. This is done by sending the  "Access-Control-Allow-Origin" header. Following is an example of a client and server peforming CORS. 

Server Code:

 <?php  
 header('Access-Control-Allow-Origin: *'); 
 $Response = array(1,2,3); 
 echo json_encode($Response);      
 ?> 


Ajax Client Code:

 <html> 

 <head> 

 <title>test</title> 

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> 

 </head> 

 <body> 

 <input type="button" value="test" onclick="testajax()" /> 

 </body> 

 <script> 

 function testajax() 

 { 

  $.ajax({ 

   crossdomain : true, 

   type : "text/plain", 

   type : "GET", 

   url : "http://www.testerzone.com/test/test.php", 

   success : function (data){ 

    alert(data); 

   }, 

   error: function (xhr, ajaxOptions, thrownError) { 

     alert(xhr.status); 

     alert(thrownError); 

     } 

  }); 

 } 

 </script> 

 </html> 

No comments:

Post a Comment