Use JSON data format in Ajax requests

Source: Internet
Author: User
Tags php array to json

 

1. Front-end page (cross-origin can be implemented using jquery's getjson function)

 

 

Note: Both HTML and PHP pages use GBK encoding.

   Function item (Num, username) {var user = encodeuri (username); // encode Chinese Characters in Ajax (JS uses utf8 format) $. getjson ("getitem. php? Callback =? ", {Num: num, // note the end comma, followed by the parameter name, followed by the parameter value User: User}, function callback (JSON) {var STR = ""; for (VAR I = 0; I <JSON. length; I ++) Alert (decodeuri (JSON [I]. name) + JSON [I]. age); // decoding is required when the Encoded chinese data is returned });}

 

 

2. backend page (implemented in PHP)

$ Callback = $ _ Get ["Callback"]; // not available <br/> $ num = $ _ Get ["num"]; <br/> $ user = iconv ("UTF-8", "GBK", urldecode ($ _ Get ["user"]); // The USER parameter passed by Ajax must be decoded first, transcode to GBK </P> <p> // assume that the $ num and $ USER Parameters are used to implement some business logic, finally, an array is generated to indicate the names and ages of some people. <br/>/* $ rs = array (<br/> array ('A' => 'zhang san ', 'B' => '21'), <br/> array ('A' => 'lily', 'B' => '22 '), <br/> array ('A' => 'wang 5', 'B' => '23') <br/> ); */</P> <p> $ arr = array (); <br/> foreach ($ RS as $ row) <br/> $ arr [] = array ('name' => urlencode (iconv ('gbk', 'utf-8', $ row ['a']), 'age' => $ row ['B']); <br/> // transcode Chinese to uft8 format before encoding, JSON cannot recognize Chinese Characters in Ajax requests <br/> $ JSON = json_encode ($ ARR); // convert the PHP array to JSON format </P> <p> echo $ callback. "(". $ JSON. ")"; // JSON data should be enclosed in parentheses (). This Code returns the information to the callback function of the front-end Js. 


 

 

Related Article

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.