ajax調用後端接口實例「ajax調用接口步驟」

Ajax調用接口並顯示返回參數

前端需要調用接口並返回結果時,可以使用Ajax來實現。菜雞程序員對其中的原理不是很了解,但是看網上很多教程很麻煩,這裡貼一個我成功實現的一個case。

  • 使用id來定位需要修改的部分
  • 點擊按鈕時觸發loadDoc()函數
  • 使用console.log(‘error’)可以在控制台打出想看的東西
  • xhttp.open(“POST”, “http://localhost:5000/users/xxxxx/me”, true);使用POST向接口發送請求,true表示異步請求
  • xhttp.setRequestHeader(‘content-type’, ‘application/json’);設置請求的header
  • xhttp.send(JSON.stringify(sendData));將變量json格式化後傳輸
  • xhttp.onreadystatechange = function()在這裡執行想要進行的html變換的操作,JSON.parse(xhttp.responseText)
<!DOCTYPE html>
<html>
<body>

<h1>XMLHttpRequest target</h1>

<button type="button" onclick="loadDoc()">Request Data</button>

<p>suggestion: <span id="demo"> </span></p>

<script>
function loadDoc() {
  console.log('error');
  var xhttp = new XMLHttpRequest();
  xhttp.open("POST", "http://localhost:5000/users/xxxxx/me", true);
  xhttp.setRequestHeader('content-type', 'application/json');
  var sendData = {"abc":123};
  //將用戶輸入值序列化成字符串
  xhttp.send(JSON.stringify(sendData));
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4) {
        var jsonObj = JSON.parse(xhttp.responseText);
        document.getElementById("demo").innerHTML = jsonObj.data.adjustPeriod
        console.log(jsonObj.data.adjustPeriod);
    }
  }
}

</script>

</body>
</html>

Ajax跨域問題解決

python中,在flask創建app實例時,添加如下代碼即可:

from flask_cors import CORS
# 創建app實例對象
    app = Flask(__name__)
    CORS(app)

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/209170.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-08 15:25
下一篇 2024-12-08 15:25

相關推薦

發表回復

登錄後才能評論