25. Vue 使用 vue-resource 發起get、post、jsonp請求的基本用法
小編:管理員 100閱讀 2022.08.19
介紹
導入 vue-resource
1.2 使用 vue-resource 發起 get、post請求
Vue 可以使用 vue-resource 發起get、post、jsonp請求,還可以使用 axios的第三方包實現實現數據的請求。
本章節來介紹如何使用vue-resource,使用flask框架編寫后端業務處理get、post、jsonp請求。
下載 vue-resourcevue-resource的Github:https://github.com/pagekit/vue-resource

訪問 https://cdn.jsdelivr.net/npm/vue-resource@1.5.1,然后右鍵保存該js文件即可。

<!-- 1.導入vue.js庫 --> <script src="lib/vue.js"></script> <!-- 2.導入vue-resource,注意:需要先引入vue.js --> <script src="lib/vue-resource@1.5.1"></script>復制1.示例:實現最簡單的get、post請求1.1 使用flask框架,編寫get、post處理業務
from flask import Flask, jsonify,request,render_template # 實例化app app = Flask(import_name=__name__) @app.route('/vue_test', methods=["GET"]) def vue_test(): return render_template('vue_test.html') @app.route('/login', methods=["GET","POST"]) def login(): method = request.method return jsonify(token=123456, gender=0, method = method) if __name__ == '__main__': app.run(debug=True)復制
使用postman調試如下:
- 執行get請求

- 執行post請求

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 1.導入vue.js庫 --> <script src="/static/vue.js"></script> <!-- 2.導入vue-resource,注意:需要先引入vue.js --> <script src="/static/vue-resource-1.5.1.js"></script> </head> <body> <div id="app"> <input type="button" value="get請求" @click="getInfo"> <input type="button" value="post請求" @click="postInfo"> <input type="button" value="jsonp請求" @click="jsonpInfo"> </div> <script> // 2. 創建一個Vue的實例 var vm = new Vue({ el: '#app', data: {}, methods: { getInfo() { // 發起get請求 // 當發起get請求之后, 通過 .then 來設置成功的回調函數 this.$http.get('/login').then(function (result) { // 通過 result.body 拿到服務器返回的成功的數據 // console.log(result.body) }) }, postInfo() { // 發起 post 請求 application/x-wwww-form-urlencoded // 手動發起的 Post 請求,默認沒有表單格式,所以,有的服務器處理不了 // 通過 post 方法的第三個參數, { emulateJSON: true } 設置 提交的內容類型 為 普通表單數據格式 this.$http.post('/login', {}, { emulateJSON: true }).then(result => { console.log(result.body) }) }, jsonpInfo() { // 發起JSONP 請求 // this.$http.jsonp('http://vue.studyit.io/api/jsonp').then(result => { this.$http.jsonp('http://127.0.0.1:5000/login').then(result => { console.log(result.body) }) } }, }); </script> </body> </html>復制
啟動Flask服務,測試三個請求如下:
- 執行GET請求

- 執行POST請求

- 執行JSONP請求

相關推薦
- Vue3(二)工程化開發方式做項目 工程化的開發方式這是開發中、大型項目的必備技能,網上資料也很多,這里只是一個簡單的綜合性的介紹。包括vue的全家桶、建立項目的幾種方式、UI庫的簡單使用等??梢院蜕弦黄腸nd方式做項目做一下對比。node.js,npm、cnpm、yarnnode.js執行 npm run serve ,…
- Hibernate Criterion 在查詢方法設計上能夠靈活的依據Criteria的特點來方便地進行查詢條件的組裝.Hibernate設計了CriteriaSpecification作為Criteria的父接口,以下提供了Criteria和DetachedCriteria.Criteria和DetachedCriteria的主要差別在于創建的形式不一樣,Criteria是在線的,所…