May 08, 2021 JSON
JSON is not much different from XML, but JSON has a wider range of applications, which is cross-domain data calls. B ecause of security issues, AJAX does not support cross-domain calls, which can be cumbersome to call data under different domain names. The following example is enough to show how php is called across domains with json.
index.html
<script type="text/javascript">
function getProfile(str) {
var arr = str;
document.getElementById('nick').innerHTML = arr.nick;
}
</script>
<body>
<div id="nick"></div>
</body>
<script type="text/javascript" src="http://www.openphp.cn/demo/profile.php"></script>
<?php
$arr = array(
'name' => 'tanteng',
'nick' => 'pony',
'contact' => array(
'email' => '[email protected]',
'website' => 'http://aa.sinaapp.com',
)
);
$json_string = json_encode($arr);
echo "getProfile($json_string)";
?>
When index.html calls profele.php, the JSON string is generated and passed in as an argument to getProfile, and then the nickname is inserted into the div, so that a cross-domain data interaction is done, isn't it particularly simple?
PhP json format and js json format js cross-domain call implementation code
Let's start with a js function
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]);
}
$arr = array (
array (
'catid' => '4',
'catname' => '程程',
'meta_title' => '程程博客'
),
array (
'catid' => '6',
'catname' => 'climber',
'meta_title' => '攀登者',
)
);
$jsonstr = json_encode($arr);
echo $jsonstr;
In this code, $arr is an array, and we convert $arr to json json_encode using a json_encode.
$arr = array (
array (
'catid' => '4',
'catname' => '程程',
'meta_title' => '程程博客'
),
array (
'catid' => '6',
'catname' => 'climber',
'meta_title' => '攀登者',
)
);
$jsonstr = json_encode($arr);
Let's build another json .html file
<SCRIPT type=text/javascript src="php_json.php"></SCRIPT>
<SCRIPT language=javascript type=text/javascript>
function loadjson(_json)
{
if(_json)
{
for(var i=0;i<_json.length;i++)
{
alert(_json[i].catname);
}
}
}
loadjson(jsonstr)
</SCRIPT>
So when we look .html json's data, loadjson (jsonstr) prompts "process" and "climber"