irpas技术客

使用原生Ajax与服务端交互(Flask)_maolele2020_ajax与flask

网络投稿 6752

使用原生Ajax与服务端交互(Flask) HTTP知识简介 HTTP概念

HTTP协议(超文本传输协议),协议详细规定了浏览器和万维网服务器之间互相通信的规则。

请求报文

结构:

请求行,如:GET /sie=utf-8 HTTP/1.1

请求头,如:Host: baidu.com

? Cookie: name=guigu

? Content-type: application/x-www-form-urlencoded

? User-Agent: chrome 83

空行,

请求体,如: username=admin&password=admin

响应报文

结构:

响应行,如:HTTP/1.1 200 OK // HTTP/1.1是HTTP版本, 200是响应状态码,OK是响应字符串

响应头,如:Content-Type: text/html;charset=utf-8

? Content-length: 2048

? Content-encoding: gzip

空行,

响应体,如:

<html> <head> <body> <h1>hello</h1> </body> </head> </html> Flask设置允许跨域

由于Ajax不允许跨域,所以需要在后端服务程序中设置允许跨域。

在设置之前,需要在当前虚拟环境下安装flask-cors:

pip install flask-cors

代码实现:

在项目的templates文件下新建index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>EasyImage</title> <style> #result{ width: 200px; height: 100px; border: solid 1px #90b; } </style> </head> <body> <button>点击发送请求</button> <div id="result"></div> <script> // 获取button元素 const btn = document.getElementsByTagName("button")[0]; const result = document.getElementById("result"); // 绑定事件 btn.onclick = function(){ // 创建对象 const xhr = new XMLHttpRequest(); // 初始化,设置请求方法和url xhr.open("GET", "http://127.0.0.1:5000/server"); // 发送 xhr.send(); // 事件绑定,处理服务端返回的结果 // on when 当...的时候 // readystate 是xhr对象中的属性,表示状态0 1 2 3 4 //(0:未初始化,1:open方法调用完毕,2:send方法调用完毕,3:服务端开始返回结果,4:服务端返回了所有结果) // change 改变 xhr.onreadystatechange = function(){ // 判断(服务端返回了所有结果) if(xhr.readyState === 4){ // 判断响应状态码 2xx为成功 if(xhr.status >= 200 && xhr.status < 300){ // 处理结果 console.log(xhr.status); // 状态码 console.log(xhr.statusText); // 状态字符串 console.log(xhr.getAllResponseHeaders()); // 所有响应头 console.log(xhr.response); // 响应体 // 设置result的文本 result.innerHTML = xhr.response; }else{ } } } } </script> </body> </html>

app.py

from flask import Flask from flask import render_template from flask_cors import cross_origin app = Flask(__name__) @app.route('/') @cross_origin() # 设置允许跨域 def index(): return render_template('index.html') @app.route('/server') @cross_origin() # 设置允许跨域 def server(): return "hello" if __name__ == '__main__': app.run(debug=True) 效果:

点击按钮前,框框中为空。 点击按钮发送后,框框中出现hello 参考了尚硅谷Ajax的教学视频。


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #ajax与flask #请求报文结构请求行如GET #sieutf8 #HTTP11请求头如Host #baiducomCookie