我有以下檔案 HTML:
<!DOCTYPE html>
<html>
<body>
<input id = "input_thing">
<button id="demo" onclick="myFunction()">Click me.</button>
<script src='script.js'></script>
JS:
function myFunction() {
var x = document.getElementById("input_thing").value;
const Http = new XMLHttpRequest();
const url=' https://*****.****.**/doctorapi/' x;
fetch(url).then(function (response) {
console.log(response.json());
document.getElementById('demo').innerHTML=response.json();
})
}
本質上,我正在嘗試列印對我發送的請求的回應。我創建的網站正在接收請求。
這是其中的一些代碼
@app.route('/doctorapi/<query>')
def next(query):
respons = query_search(query)
respons=str(respons)
response = make_response(jsonify(
{
"medical_response":respons,
"query":query
}
))
return response
當我打開瀏覽器時,我看到了回應。但是,JS 沒有得到那個 JSON 和日志以及空字串。我該如何解決?發送請求的正確方式是什么>
uj5u.com熱心網友回復:
json()回應物件的功能是異步的。因此它回傳一個該Promise型別的物件。要獲得最終結果,它必須與await關鍵字一起預期或在隨后的then.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name="search-form">
<input type="text" name="query" />
<button type="submit">Click me</button>
</form>
<output name="search-result"></output>
<script type="text/javascript">
(() => {
const formElem = document.querySelector('form[name="search-form"]');
formElem.addEventListener('submit', event => {
event.preventDefault();
fetch(`/doctorapi/${encodeURIComponent(event.target.query.value)}`)
.then(resp => resp.json())
.then(data => {
const outElem = document.querySelector('output[name="search-result"]');
outElem.innerHTML = JSON.stringify(data);
});
});
})()
</script>
</body>
</html>
@app.route('/doctorapi/<query>')
def search(query):
data = 'my-search-result'
return jsonify(query=query, results=data)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/352721.html
標籤:javascript html 烧瓶
上一篇:帶有臨時檔案的燒瓶發送檔案
