ajax調用后端接口實例 ajax調用接口步驟

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><h3>XMLHttpRequest target</h3><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 = https://www.cnfyg.com/shcs/{"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.adjustPeriodconsole.log(jsonObj.data.adjustPeriod);}}}</script></body></html>Ajax跨域問題解決python中 , 在flask創建app實例時 , 添加如下代碼即可:
from flask_cors import CORS# 創建app實例對象app = Flask(__name__)CORS(app)

    推薦閱讀