php code that USES JSON for data transfer across domains

  • 2020-05-10 17:52:47
  • OfStack

Background profile. php code:
 
<?php 
$arr = array( 
'firstname' => iconv('gb2312', 'utf-8', ' If you are the '), 
'lastname' => iconv('gb2312', 'utf-8', ' You are the one '), 
'contact' => array( 
'email' =>'fcwr@ofstack.com', 
'website' =>'//www.ofstack.com', 
) 
); 
// will 1 An array JSON 
$json_string = json_encode($arr); 
// Note here that double quotes can handle variables inside while single quotes do not  
echo "getProfile($json_string)"; 
?> 

It should be pointed out that Chinese characters cannot be encode under non-UTF-8 encoding, and the result will be null. Therefore, if you use gb2312 to write PHP code, then you need to use iconv or mb to UTF-8 to json_encode.
index.html code:
 
<script type="text/javascript"> 
function getProfile(str) { 
var arr = str; 
document.getElementById("firstname").innerHTML = arr.firstname; 
} 
</script> 
<body> 
<div id="firstname"></div> 
</body> 
<!--  use JSON Implement cross-domain data invocation, where" profile.php "To" http:// In addition 1 A domain name /profile.php "Is more cross-domain --> 
<script type="text/javascript" src="profile.php"></script> 

If the data in JSON format is directly assigned to the variables in javascript, it will become an array, and then it will be very convenient to operate. Here, if XML is used as the data transmission, the subsequent operation will be inconvenient.
Obviously, when index.html calls profile.php, the JSON string is generated, passed to getProfile as a parameter, and then the nickname is inserted into div, so that one cross-domain data interaction is complete
Call index html
Output: non - sincere

Related articles: