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代碼:
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,無能為力。目前前后端均我一人編寫,暫不考慮慮此情況。
上面是我整理給大家的,希望今后會對大家有幫助。
相關(guān)文章:
jQuery+ajax讀取json并排序方法詳解
jQuery+Ajax驗證用戶名
關(guān)于AJAX中 XML 的實例講解
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com