亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

原生JS實(shí)現(xiàn)Ajax跨域請(qǐng)求flask響應(yīng)內(nèi)容

 更新時(shí)間:2017年10月24日 09:22:25   作者:嵐漾憶雨  
這篇文章主要為大家詳細(xì)介紹了JS實(shí)現(xiàn)Ajax跨域請(qǐng)求flask響應(yīng)內(nèi)容,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

Ajax方法好,網(wǎng)站感覺(jué)跟高大上,但由于Js的局限,跨域Ajax無(wú)法實(shí)現(xiàn),這里,講一下解決辦法,前提是需要能夠自己可以控制flask端的響應(yīng)。

主要技術(shù):

修改服務(wù)器相應(yīng)的相應(yīng)頭,使其可以相應(yīng)任意域名。and設(shè)置響應(yīng)頭,使其能夠相應(yīng)POST方法。

實(shí)現(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測(cè)試代碼:

<!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ù),沒(méi)有此句post的內(nèi)容無(wú)法傳遞
  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>

無(wú)法控制響應(yīng)頭

對(duì)于這種情況,get請(qǐng)求可以使用jquery完成,post,無(wú)能為力。目前前后端均我一人編寫,暫不考慮慮此情況。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論