Some days back I had posted a tutorial about parsing JSON data with jQuery .getJSON(). In this post I want to explain about ‘How to use JSON callback and to display cross domain data with jQuery’. It’s simple and useful.
Just copy and paste this following code between <body> tag. You can display another domain data.
1 2 3 4 5 | <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" src="http://domian.com/domain.json.js"></script> <link href="http://domian.com/domain_css.css" rel="stylesheet" type="text/css"> <ol id="dataJson" class="jsonbox"></ol> |
domain.json.js
Javascript code read the JSON file.
1 2 3 4 5 6 7 8 9 10 11 12 13 | $(document).ready(function() { $.getJSON("http://domian.com/json.php?count=5&jsoncall=?",function(data) { $.each(data.posts, function(i,data) { var jsondata ="<li>"+data.message+"</li>"; $(jsondata).appendTo("ol#dataJson"); }); } ); return false; }); |
json.php
Contains PHP code displaying results from Messages table in JSON format.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php include('config.php'); if($_GET['count']) { $count=$_GET['count']; $count=mysql_real_escape_string($count); $sql=mysql_query("select msg from messages order by msg_id desc limit $count"); echo $_GET["jsoncall"].'({"posts": ['; while($row=mysql_fetch_array($sql)) { $message=$row['message']; echo ' { "message":"'.$message.'", },'; } echo ']})'; } ?> |
domain_css.css
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | *{margin:0px; padding:0px;} ol.jsonbox { font-family:"lucida grande",tahoma,verdana,arial,sans-serif; font-size:11px; color:#FFFFFF; list-style:none; width:300px; padding:10px 10px 25px 10px; background:url(http://domain.com/jsonlogo.png) bottom right no-repeat; background-color:#333333; text-align:left } ol.jsonbox li { padding-bottom:4px} ol.jsonbox li a{color:#80c8e5; text-decoration:none} ol.jsonbox li a:hover{color:#80c8e5; text-decoration:underline} |