Sort out an example in json format and call between phpjson format and jsjson (the legendary cross-origin JavaScript call). first look at a js function.
The code is as follows:
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.
Let's take a look at a piece of code.
The code is as follows:
$ Arr = array (
Array (
'Catid' => '4 ',
'Catname' => 'chengcheng ',
'Meta _ title' => 'Cheng Cheng 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 how php processes 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 call each other.
Create a new php_json.php file.
The code is as follows:
The code is as follows:
$ Arr = array (
Array (
'Catid' => '4 ',
'Catname' => 'chengcheng ',
'Meta _ title' => 'Cheng Cheng blog'
),
Array (
'Catid' => '6 ',
'Catname' => 'climber ',
'Meta _ title' => 'crawler ',
)
);
$ Jsonstr = json_encode ($ arr );
----- The following is written outside the php range -----
Var jsonstr = <? = $ Jsonstr? >;
PS: var jsonstr = <? = $ Jsonstr? >. This is to assign the value of json data to the jsonstr variable.
Create another json.html file.
The code is as follows:
The code is as follows: