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 ." } ] |