您好,登錄后才能下訂單哦!
Ajax方法好,網(wǎng)站感覺跟高大上,但由于Js的局限,跨域Ajax無法實現(xiàn),這里,講一下解決辦法,前提是需要能夠自己可以控制flask端的響應(yīng)。
主要技術(shù):
修改服務(wù)器相應(yīng)的相應(yīng)頭,使其可以相應(yīng)任意域名。and設(shè)置響應(yīng)頭,使其能夠相應(yīng)POST方法。
實現(xiàn)代碼:
這里先放flask代碼:
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' #響應(yīng)POST return rst
html測試代碼:
<!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"); #這句話可以發(fā)送post數(shù)據(jù),沒有此句post的內(nèi)容無法傳遞 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>
無法控制響應(yīng)頭
對于這種情況,get請求可以使用jquery完成,post,無能為力。目前前后端均我一人編寫,暫不考慮慮此情況。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。