【发布时间】:2019-07-26 11:24:04
【问题描述】:
提交帖子后,我无法显示它们。我不知道为什么不工作。 getPosts() 功能在我刷新页面时工作,一切正常。但是在我提交帖子后,我无法获得它们。我在后端使用 JSON 假服务器。
// On load
document.addEventListener('DOMContentLoaded', function () {
getPosts();
});
// Sumbit post
document.querySelector('#wrapper-form').addEventListener('click', submitPost);
// Function Helpers
function submitPost(e) {
if(e.target.dataset.role === 'submit-post') {
http.submitPost();
getPosts();
}
e.preventDefault();
}
// Get posts
function getPosts() {
http.getPosts()
.then(response => {
ui.populateList(response);
})
.catch(err => console.log(err));
}
以下是请求:
// Get
getPosts() {
return new Promise((resolve, reject) => {
this.xhr.open('GET', 'http://localhost:3000/posts', true);
this.xhr.onload(
const response = JSON.parse(this.xhr.responseText);
if(this.xhr.status === 200 && this.xhr.readyState === 4) {
resolve(response);
} else {
reject('Some Error' + status);
}
);
this.xhr.send();
});
}
// Submit
submitPost() {
return new Promise((resolve, reject) => {
const data = {
title: document.querySelector(UiSelectors.titleInput).value,
body: document.querySelector(UiSelectors.bodyInput).value
};
this.xhr.open('POST', 'http://localhost:3000/posts', true);
this.xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');
this.xhr.send(JSON.stringify(data));
});
}
【问题讨论】:
-
你能解释一下吗?您的意思是提交帖子后,您无法获取帖子?
-
原因可能是您在提交时的 getPosts() 在 http.submitPost() 之前触发。尝试使用承诺确保 getPosts() 仅在 http.sumitPost() 完成后触发
-
我发布解决方案
标签: javascript ajax asynchronous post get