
可悲的是,我没有避免这些错误。我希望这可以帮助其他人在尝试更新网页而不完全下载新版本时避免它们。我最终得到的代码似乎有效:
async function fetchdbsingle(url, str) {
const datatosend = str;
console.log('fetchdbsingle: ' + str);
try {
const response = await fetch(url, {
method: 'post',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: datatosend
});
if (!response.ok) {
throw new error('network response was not ok');
}
const data = await response.json();
return data;
} catch (error) {
console.error('error fetching data:', error);
throw error; // re-throw the error to be handled by the caller
}
}
await 在异步函数内工作,以确保数据在尝试访问之前已到达。如果您需要从普通代码调用异步函数,语法为 .then:
fetchDbSingle(url, str).then(data => {
console.log("Received data:", data);
// Use the data here
}).catch(error => {
console.error("Error fetching data:", error);
});
如果您尝试在不使用此特殊语法的情况下访问数据,则数据将是未定义的,因为您是在数据到达之前访问它。
如果您尝试访问标记位置之外的数据,它将是未定义的。
在我的程序中,fetch() 正在调用读取数据库的 php 脚本。
这里有一些警告,对于有经验的人来说可能毫无意义,但我希望我早点知道:
如果有人有兴趣知道我为什么提到上述警告,我可以写一篇文章,介绍我所犯的错误以及我如何花了一周的时间来纠正这些错误,然后你就可以咯咯笑并感到优越。
以上就是要避免的 fetch() 和 XMLHttp 错误的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号