PHP returns json data to jquery. Json-format data is the data we always use in application development. json data is used when you submit data with jquery or when you submit data with APIs, how does PHP return json data to json data, for example, if json data is used when you submit data with jquery or when you submit data with APIs, how does PHP return json data to jquery? next I will introduce it to you.
To operate json data in jquery, we directly $. parseJSON (returnString ).
Example
The code is as follows: |
|
$ (Function (){ $ ('# Send'). click (function (){ $. GetJSON ('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 ." } ]
|
The json data mentioned above is fixed. how can we return json data using php?
Php output JSON format method
Add
Header ('content-type: text/json ');
This header indicates that the output type of this file is json. The most common form we see is the verification code-php output verification image. sometimes php can output css files, js files and other interesting things. Okay. let's test it.
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 ); ?> |
Instance
The data read from the database is in json format.
The code is as follows: |
|
Tutorial provided by the first php network-generate the data read by the database in json format Script
|