How does PHP return data in json format? json data is a special data format and can interact with data in real time, next I will introduce how PHP returns data in json format. Some of our common websites return JSON format when doing ajax...
How does PHP return data in json format? json data is a special data format and can interact with data in real time, next I will introduce how PHP returns data in json format.
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: |
|
Header ('content-type: text/json '); |
Sample code:
| The code is as follows: |
|
<? 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: |
|
$ (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 + ='
'+ Comment ['username'] + ': '+ Comment ['content'] +' '; }) ('{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: |
|
[ { "Username": "Zhang San ", "Content": "sofa ." }, { "Username": "Li Si ", "Content": "bench ." }, { "Username": "Wang Wu ", "Content": "floor ." } ] |