与后端交互
三种方式
方式一:jquery的ajax方法发送请求(基本不用了)
方式二:js官方提供的fetch方法(XMLHttpRequest)(官方的,用的也少)
方式三:axios第三方,做ajax请求
代码测试
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!-- <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>--> </head> <body> <div id="app"> {{text}} </div> </body> <script> var vm = new Vue({ el: '#app', data: { text: '', }, created() { // 方式一: //向后端发请求,拿数据,拿回来赋值给text // $.ajax({ // url:'http://127.0.0.1:5000/', // type:'get', // success:(data) =>{ // console.log(data) // this.text=data // } // }) // 方式二:js原生的fetch // fetch('http://127.0.0.1:5000/').then(res => res.json()).then(res => { // console.log(res) // this.text=res.name // // }) // 方式三 axios axios.get('http://127.0.0.1:5000').then(data => { console.log(data.data) this.text=data.data.name }) } }) </script> </html>
案例
python
from flask import Flask,make_response,jsonify app=Flask(__name__) @app.route('/') def index(): # 跨域问题 obj=make_response(jsonify({'name':'lqz is handsome','age':19})) obj.headers['Access-Control-Allow-Origin']='*' return obj @app.route('/films') def films(): # 跨域问题 import json with open('./res.json','r',encoding='utf-8') as f: res=json.load(f) obj = make_response(jsonify(res)) obj.headers['Access-Control-Allow-Origin']='*' return obj if __name__ == '__main__': app.run()
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./js/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> <div id="app"> <ul> <li v-for="film in films_list"> <p>电影名字是:{{film.name}}</p> <img :src="film.poster" alt="" width="100px" height="150px"> <p>电影介绍:{{film.synopsis}}</p> </li> </ul> </div> </body> <script> var vm = new Vue({ el: '#app', data: { films_list:[] }, created() { // 方式三 axios axios.get('http://127.0.0.1:5000/films').then(res => { console.log(res.data) this.films_list=res.data.data.films }) } }) </script> </html>