How does PHP return data in json format?

Source: Internet
Author: User

Some websites usually return JSON-format data when using ajax:

Php output JSON format


Obviously not what you want. Or a string. How do I implement it? In fact, it is very easy to add the following code to the PHP file header:

The code is as follows: Copy code

Header ('content-type: text/json ');

Sample code:

The code is as follows: Copy code

<? Php
Header ('content-type: text/json ');

$ Fruits = array (
"Fruits" => array ("a" => "orange", "B" => "banana", "c" => "apple "),
"Numbers" => array (1, 2, 3, 4, 5, 6 ),
"Holes" => array ("first", 5 => "second", "third ")
);
Echo json_encode ($ fruits );
?>

Let's take a look at jquery.

The code is as follows: Copy code


$ (Function (){
$ ('# Send'). click (function (){
$. GetJSON ('http: // blog.meituo.net/wp-content/uploads/php_return_json/test.js', function (data ){
$ ('# ResText'). empty ();
Var html = '';
$. Each (data, function (commentIndex, comment ){
Html + = '<div class = "comment"> })
('{Restext'{.html (html );
})
})
})

What you need to do is to store the data in a. json or. js file in the correct format. The following is an example of the data transmitted in json format.

 

The code is as follows: Copy code
[
  {
"Username": "Zhang San ",
"Content": "sofa ."
},
  {
"Username": "Li Si ",
"Content": "bench ."
},
  {
"Username": "Wang Wu ",
"Content": "floor ."
  }
]

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.