[英]AJAX request not calling python-flask method
我正在嘗試使用 XMLHttpRequest() 從 JavaScript 調用 AJAX 請求到 flask 服務器,但問題是request.open()
似乎不起作用,因為 python function 沒有被調用。
.js代碼是
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".messaging-channel").onclick = () => {
const channelName = document.querySelector(".messaging-channel").innerHTML;
var request = new XMLHttpRequest();
request.open("POST", "/channel");
window.alert(`${channelName}`);
request.onload = () => {
const response = JSON.parse(request.responseText);
const messages = response.channel;
window.alert(`${messages} are the messages.`);
};
};
});
flask 方法是
@app.route("/channel", methods=["POST", "GET"])
def channel():
print("Working python\n\n")
return jsonify({"channel": "Working"})
這兩個文件都已連接並且window.alert(`${channelName}`);
在 .js 文件中執行良好。 雖然請求沒有調用 python function。我還通過 safari 在調試器上檢查了這個,它會說:
arguments:TypeError:在此上下文中無法訪問“arguments”、“callee”和“caller”。
來電者:TypeError:在此上下文中無法訪問“arguments”、“callee”和“caller”。
您必須使用request.send()
向服務器發送請求。
使用GET
、 POST
、 PUT
、 DELETE
、 HEAD
等都沒有關系。
from flask import Flask, render_template_string, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string('''
<button class="messaging-channel">SUBMIT</button>
<script>
document.addEventListener("DOMContentLoaded", () => {
document.querySelector(".messaging-channel").onclick = () => {
const channelName = document.querySelector(".messaging-channel").innerHTML;
var request = new XMLHttpRequest();
request.open("POST", "/channel");
window.alert(`${channelName}`);
request.onload = () => {
const response = JSON.parse(request.responseText);
const messages = response.channel;
window.alert(`${messages} are the messages.`);
};
request.send();
};
});
</script>''')
@app.route("/channel", methods=["POST", "GET"])
def channel():
print("Working python\n\n")
return jsonify({"channel": "Working"})
if __name__ == '__main__':
app.run()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.