Php code for cross-Origin data transmission using JSON

Source: Internet
Author: User

Background profile. php code:
Copy codeThe Code is as follows:
<? Php
$ Arr = array (
'Firstname' => iconv ('gb2312', 'utf-8', 'sincerity '),
'Lastname' => iconv ('gb2312', 'utf-8', 'Do not disturb '),
'Contact '=> array (
'Email '=> 'fcwr @ jb51.net ',
'Website' => 'HTTP: // www.jb51.net ',
)
);
// JSON
$ Json_string = json_encode ($ arr );
// Note that double quotation marks can be used to process the variables in the variable.
Echo "getProfile ($ json_string )";
?>

It should be noted that, in non-UTF-8 encoding, Chinese characters will not be encode, the results will be null, So if you use gb2312 to write PHP code, then we need to use iconv or mb to convert the content containing Chinese characters into UTF-8 and then perform json_encode.
Front index.html code:
Copy codeThe Code is 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-Origin data calling. For example, you can change "profile. php" to "http: // another domain name/profile. php" to see cross-Origin data calling. -->
<Script type = "text/javascript" src = "profile. php"> </script>

The JSON-format data is directly assigned to the variables in javascript and becomes an array. The next operation will be very convenient. If XML is used for data transmission, subsequent operations will be inconvenient.
Obviously, when index.html calls profile. php, The JSON string is generated and passed into getProfile as a parameter, and then the nickname is inserted into the div. This completes a cross-Origin data interaction.
Call index.html
Output: FEICHENG

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.