我已經嘗試了幾天,作為模塊創建的函式可以回傳資料。
我使用燒瓶并在頁面中將模塊加載到標題中。
<script src="{{url_for('static', filename = 'js/modules.js')}}"></script>
在我第一次嘗試 modules.js 檔案時,我有這個功能:
function send_to_backend_old(data){
let coucou = fetch('/toronto', {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
response.json().then(function(data_received) {
return data_received;
}).then((data_received)=>{
return data_received;
})
});
return coucou
在我呼叫函式時,在 javascript 部分的 html 頁面中,此資料未到達。
<button type="button" class="btn btn-primary btn-sm" onclick="pruebas_fetch_to_backend();">fetch módulo</button>
function pruebas_fetch_to_backend(){
let datos_json = {};
datos_json.url_api = '/toronto'
datos_json.test1 = 'valor1'
datos_json.test2 = 'valor2'
console.log("---------------------------------------------")
riri = send_to_backend(datos_json)
console.log("valor de riri: " JSON.stringify(riri))
console.log("---------------------------------------------")
}
另一項測驗如下:
async function send_to_backend(data) {
let apiResponse = await fetch("/toronto", {
method: 'post',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
let response = apiResponse.json();
// Since we waited for our API to respond using await
// The response variable will return the response from the API
// And not a promise.
console.log(response);
return Promise.all(response);
}
當我從 html 頁面中的 javascript 代碼呼叫函式時,如何獲得回應?
uj5u.com熱心網友回復:
類似fetch(...)
和.json()
的函式是異步函式。這些回傳一個 Promise 型別的物件。這意味著函式的結果不會立即回傳。可以等待最終結果,然后可以使用
。await
使用 await 關鍵字的函式必須定義為異步的。
async function sendFetchRequest() {
const data = await fetchJSONData({
test1: 'value1',
test2: 'value2'
});
console.log(data);
}
但是,作為 的替代方法await
,也可以將回呼函式傳遞給.then(...)
呼叫。那么同步函式也可以用來呼叫異步函式。
在這種情況下,同步函式回傳一個Promise
物件,該物件由異步 fetch 呼叫的回呼產生。然后在上述函式中等待回傳的物件,并在獲得最終結果后轉儲。
function fetchJSONData(data) {
return fetch('/echo', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => {
return resp.ok && resp.json()
});
}
為了捕獲錯誤,可以選擇使用 try-catch 塊,以及在.catch(...)
.
所以一個簡單的例子看起來像這樣。
JS (靜態/js/module.js)
function fetchJSONData(data) {
return fetch('/echo', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => {
return resp.ok && resp.json()
});
}
HTML (模板/index.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Index</title>
<script src="{{url_for('static', filename='js/module.js')}}"></script>
</head>
<body>
<button type="button" onclick="sendFetchRequest()">Click me!</button>
<script type="text/javascript">
async function sendFetchRequest() {
const data = await fetchJSONData({
test1: 'value1',
test2: 'value2'
});
console.log(data);
}
</script>
</body>
</html>
燒瓶(app.py)
from flask import (
Flask,
jsonify,
render_template,
request,
)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.post('/echo')
def echo():
return jsonify(request.json)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482471.html
標籤:javascript 烧瓶 拿来
上一篇:FlaskFormvalidate_on_submit總是回傳false
下一篇:如何在燒瓶中輸出html檔案