我有以下代码:
<button type="button" onclick="getHistory()">Refresh</button>
</p>
<br>
<p id="textList">List of texts:</p>
<br>
<p id="textHistory"></p>
<br>
<br>
</div>
<script>
// Gets a list of phone numbers
function getHistory(){
var success = false;
// Assemble and send the URL to the Twilio API handler
//alert(message); // debugging
var url = 'https://tools.cyntrx.net/GetHistory'
//var url = 'http://localhost:8000/GetHistory
let response = await fetch(url);
if (response.ok) { // If HTTP-status is 200-299
// Get the response body
let data = await response();
document.getElementById("textHistory").innerHTML = data;
} else {
alert("HTTP-Error: " + response.status);
}
if (success) {
alert("Message sent! (" + displayMsg + ")"); // Alert user of success
}
}
</script>当我尝试运行它时,页面会加载,但当我单击按钮时,会得到ReferenceError: getHistory is not defined。
我不确定我错过了什么。
发布于 2020-12-10 20:58:12
在不使用async关键字声明函数的情况下使用await。所以你的函数是:
async function getHistory(){
//Your codes go here
let response = await fetch(url);
//Other codes
}发布于 2020-12-10 21:31:55
这是因为在注册onclick事件时不会加载<script>。不要在onclick中调用函数,而是为按钮指定一个id,并在脚本中添加一个事件侦听器,如document.getElementById("buttonID").addEventListener("click", getHistory);
https://stackoverflow.com/questions/65234508
复制相似问题