PHP code _php tips for cross-domain transfer of data using JSON

Source: Internet
Author: User
Tags domain transfer
Background profile.php Code:
Copy Code code as follows:

<?php
$arr = Array (
' FirstName ' => iconv (' gb2312 ', ' utf-8 ', ' not honest '),
' LastName ' => iconv (' gb2312 ', ' utf-8 ', ' Don't Disturb '),
' Contact ' => Array (
' Email ' => ' fcwr@jb51.net ',
' website ' => ' http://www.jb51.net ',
)
);
Converts an array of JSON
$json _string = Json_encode ($arr);
Notice here that double quotes can handle variables inside, and single quotes don't
echo "GetProfile ($json _string)";
?>

It should be pointed out that, in the UTF-8 encoding, the Chinese characters will not be encode, the result will come out null value, so if you use gb2312 to write PHP code, then you need to use Iconv or MB content to UTF-8 and then Json_encode.
Front index.html Code:
Copy Code code as follows:

<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 to implement Cross-domain data calls, where "profile.php" is changed to "http://another domain/profile.php" to see the Cross-domain-->
<script type= "Text/javascript" src= "profile.php" ></script>

Assigning JSON-formatted data directly to a variable in JavaScript becomes an array, which makes it easy to manipulate, and the next step is inconvenient if you use XML as a data transfer.
Obviously, when Index.html calls Profile.php, the JSON string is generated and passed in GetProfile as a parameter, and then the nickname is inserted into the Div, so that a cross-domain data interaction is completed
Call index.html
Output: Non-prudential

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.