Getting Started with JSON's and php
I had been using xml for a while now. At the beginning of the week I had an idea to send data as a string in a format like a javascript object. I didn't know it was called a JSON. The next day I was reading through lxer (a linux news site) and came across an article on using php with XML or JSON. Since I didn't know what a JSON was I looked it up. Wow just what I wanted to use. It only talked about using it from a file where as I wanted to use it more like ajax. I was looking around for documentation on this and found a bunch of misinforming articles. I put together some tests and I think I have a good working example.
- <?php if(count($_REQUEST)==0){?><!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
- <title>JSON TEST</title>
- <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
- <script>
- $(function()
- {var arr=new Array('one','two','three');
- data={'arr':arr}
- $.ajax(
- {
- dataType:'json',/* Expected return type (seen bad documentation out there saying to set this as POST)*/
- type:'post',/* How it is sent POST or GET */
- data:'json='+JSON.stringify(data),/* Because php expects POST or GET data to be in a form like this name=value */
- success:parse
- });
- });
- function iterate(arr)
- {var html='';
- $(arr).each(function(i,val)
- {html+=','+val;
- });
- return html;
- }
-
- function iterate_2(arr)
- {var html='';
- $.each(arr,function(i,val)
- {html+=','+val;
- });
- return html;
- }
-
- function iterate_for(arr)
- {var html='';
- for(var i=0;i<arr.length;i++)
- {html+=','+arr[i];
- }
- return html;
- }
-
- /*Wow I can use a returned json object without parsing so cool? */
- function parse(json)
- {var html='';
- html+=iterate_for(json['arr']);
- html+=iterate(json.arr);
- html+=iterate_2(json['more']['arr']);
- $('body').html($('body').html()+html)
- }
- </script>
- </head>
- <body>
- JSON TEST
- </body>
- </html>
- <?php exit();}
- $test=array();
- $test['arr']=array('one','two','three');
- /*Parse a json object making it into a php object*/
- $json=json_decode($_REQUEST['json']);
- $json->more=$test;
- /*Return a JSON object*/
- header('Content-Type: text/javascript; charset=utf-8');
- echo json_encode($json,JSON_PRETTY_PRINT);
- ?>