Advertisement
benshepherd

PHP JSON Example

May 17th, 2013
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.32 KB | None | 0 0
  1. <?php
  2.    
  3.     if(isset($_GET['getjson'])) {
  4.        
  5.         $arr = array(
  6.             array (
  7.                 "name" => "Moon trance",
  8.                 "artist" => "Lindsey Stirling",
  9.                 "length" => "452"
  10.             ),
  11.             array (
  12.                 "name" => "Crystalize",
  13.                 "artist" => "Lindsey Striling",
  14.                 "length" => "349"
  15.             )
  16.         );
  17.        
  18.        
  19.         die(json_encode($arr));
  20.     };
  21.    
  22. ?>
  23. <!DOCTYPE html>
  24. <html xmlns="http://www.w3.org/1999/xhtml">
  25. <head>
  26. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  27. <title>JSON Test</title>
  28. <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  29. <script>
  30.  
  31.     function doJson() {
  32.        
  33.         //Notify users
  34.         $("#text").html("Fetching...");
  35.        
  36.         $.get("<?php echo basename($_SERVER['PHP_SELF']); ?>?getjson=1", function(data) {
  37.            
  38.             var obj = JSON.parse(data);
  39.            
  40.             for(var i = 0; i < obj.length; i++) {
  41.                 $("#text").append(
  42.                     "<p>"+(i+1)+":<br>" +
  43.                     "name: " + obj[i].name + "<br>" +
  44.                     "artist: " + obj[i].artist + "<br>" +
  45.                     "length: " + obj[i].length + "<br></p>"
  46.                 );
  47.             }
  48.                    
  49.         });
  50.                    
  51.     }
  52.    
  53.     function decodeHtml(x) {
  54.         var y = document.createElement("textbox");
  55.         y.innerHTML = x;
  56.         return y.value;
  57.     }
  58.  
  59. </script>
  60. </scipt>
  61. </head>
  62.  
  63. <body>
  64.     <input type="button" onclick="doJson()" value="Do JSON" /><br />
  65.     <p id="text">
  66.    
  67.     </p>
  68. </body>
  69. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement