- The first thing to know is the data format used for background and front-end interaction.
Generally choose JSON, because the perfect fit with JS.
- Data returned in the background is serialized
Returning serialized data in the view method of the/homepagerecommend route
Dict = {"A": 1, "B": 2}
1) Import JSON json.dumps (DICT) 2) from Flask import jsonifyjsonify (dict) #在调用jsonfiy sometimes error, because the Jsonify object must be Dict
The main difference between the two serialization methods is that the jsonify format is more aesthetically pleasing
- Using Jquary to deserialize JSON on the front end
$.getjson ('/homepagerecommend' , function (data) { // returned from flask alert (data.a) //Browser popup Displays the value of dict["A" returned by the backend, this time is 1
}
) The Getjson function has three parameters //The first is the URL of the data returned bythe back end//The second is to be returned to the server is optional//The third is the deserialized data for the fetch function to proceed with the operation
- Then you can use JS to do what you want to do with the data.
Summary: Flask Background to the front-end JS data, need to pay attention to serialization and deserialization
Python flask data to JS