Function jsontest ()
- {
- Var json = [{'username': 'Crystal ', 'userage': '20'}, {'username': 'Candy', 'userage ': '24'}];
- Alert (json [1]. username );
Var json2 = [['crystal ', '20'], ['Candy', '24'];
- Alert (json2 [0] [0]);
- }
This function, the First alert (json [1]. username); will prompt "candy ". A json variable is an array object. Therefore, you must use the format obj. username for calling. The second alert (json2 [0] [0]); "crystal" is displayed ". The json2 variable is in full json format. Json and json2 variables have the same effect, but json2 is much simpler than json. This is the json format of JavaScript. Let's take a look at the json format in php. first look at a piece of code:
$ Arr = array (
- Array (
- 'Catid' => '4 ',
- 'Catname' => 'rongrong ',
- 'Meta _ title' => 'Rong Rong blog'
- ),
Array (
- 'Catid' => '6 ',
- 'Catname' => 'climber ',
- 'Meta _ title' => 'crawler ',
- )
- );
- $ Jsonstr = json_encode ($ arr );
- Echo $ jsonstr;
In this code, $ arr is an array. We use json_encode to convert $ arr to json format. This code will output: [{"catid": "4", "catname": "\ u7a0b \ u7a0b", "meta_title ": "\ u7a0b \ u7a0b \ u535a \ u5ba2" },{ "catid": "6", "catname": "climber", "meta_title ": "\ u6500 \ u767b \ u8005"}] this is php's processing of json data. For json data, php can also use the json_decode () function to convert json data into arrays. For example, in the above code, we use the json_decode function for processing. The above array is printed.
- $ Jsonstr = json_encode ($ arr );
- $ Jsonstr = json_decode ($ jsonstr );
- Print_r ($ jsonstr );
Next, let's take a look at how php json data and js json data are called each other. Create the php_json.php file:
$ Arr = array (
- Array (
- 'Catid' => '4 ',
- 'Catname' => 'rongrong ',
- 'Meta _ title' => 'Rong Rong blog'
- ),
Array (
- 'Catid' => '6 ',
- 'Catname' => 'climber ',
- 'Meta _ title' => 'crawler ',
- )
- );
- $ Jsonstr = json_encode ($ arr );
- ----- The following is written outside the php range -----
- Var jsonstr = <? = $ Jsonstr? >;
Note: var jsonstr = <? = $ Jsonstr? >. This is to assign the value of json data to the jsonstr variable. Create another file json.html:
|