The Ajax method is good and the website feels high-end. However, due to the limitations of Js, cross-domain Ajax cannot be implemented. Here, let’s talk about the solution. The premise is that you need to be able to control the response on the flask side. This article mainly introduces the JS implementation of Ajax cross-domain request flask response content in detail. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Main technology:
Modify the corresponding header of the server so that it can correspond to any domain name. and sets the response header so that it can correspond to the POST method.
Implementation code:
Put the flask code here first:
from flask import make_response @app.route('/test',methods=['get','post']) def Test(): if request.method=='GET': rst = make_response('aaa') rst.headers['Access-Control-Allow-Origin'] = '*' #任意域名 return rst else: rst = make_response('bbb') rst.headers['Access-Control-Allow-Origin'] = '*' rst.headers['Access-Control-Allow-Methods'] = 'POST' #响应POST return rst
html Test code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <span id="ss">test get</span> <button onclick="getAjax()">click</button> <p id="time">test post</p> <input type="submit" value="click" onclick="getPostAjax()"> <script> function getPostAjax() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function () { if(xmlhttp.readyState=4 && xmlhttp.status ==200 ) { document.getElementById("time").innerText = xmlhttp.responseText; } } xmlhttp.open("POST","http://localhost:5000/test",true); xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); #这句话可以发送post数据,没有此句post的内容无法传递 xmlhttp.send(); } function getAjax() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange=function () { if(xmlhttp.readyState==4 && xmlhttp.status == 200){ document.getElementById("ss").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","http://localhost:5000/test",true); xmlhttp.send(); } </script> </body> </html>
Unable to control the response header
For this situation, the get request can be completed using jquery, post, nothing can be done.
Have you learned it? Hurry up and try it out.
Related recommendations:
The perfect solution for Ajax cross-domain requests that COOKIE cannot bring
Detailed examples of the principles of Ajax cross-domain requests
Examples explain four methods of AJAX cross-domain request data
The above is the detailed content of JS implements Ajax cross-domain request flask response content. For more information, please follow other related articles on the PHP Chinese website!