[英]Javascript creates dynamic html input not staying after form submission
[英]Dynamic content not updating after form submission in JavaScript
它在我再次點擊保存按鈕后顯示,所以基本上它落后了一步,它更新數據庫但在第二次點擊后加載。 我的代碼肯定有問題:
const fetchTweets = async () => {
let tweets = await axios.get(url);
return tweets.data.response;
}
然后是在頁面加載時調用的 function:
const showTweets = async () => {
let tweets = await fetchTweets();
let list = ''
let tweetsElement = document.querySelector('#tweets')
for(let tweet of tweets) {
list += tweetFormat(tweet);
}
tweetsElement.innerHTML = list;
}
showTweets()
但是當我使用這個提交處理表單時,即使我正在調用showTweets() function,它也不會更新頁面:
const tweetFormElement = document.querySelector('#tweet-create-form');
document.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(event.target);
const url = event.target.getAttribute('action');
const method = event.target.getAttribute('method');
axios({
method: method,
url: url,
data: formData
}).then((res) => {
console.log(res);
})
showTweets() // <-- calling it here
});
當我再次單擊提交時,數據顯示在頁面上,但隨后它更新了數據庫兩次。 請如果有人可以提供幫助。
在加載推文之前,您無需等待請求完成。
將showTweets
.then
:
axios({
method: method,
url: url,
data: formData
}).then((res) => {
console.log(res);
showTweets()
})
此外,您可能只想將提交偵聽器添加到tweetFormElement
而不是整個文檔:
tweetFormElement.addEventListener('submit', // ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.