【问题标题】:Ajax - can't display posts after i submitAjax - 我提交后无法显示帖子
【发布时间】: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


【解决方案1】:

我想通了:

http.submitPost()
 .then(response => {
   getPosts();
});

显然我的新手程序员技能不知道你不能同时有 2 个请求。所以我需要它先提交,然后在我提交后获取帖子。

首先我做到了:

function submitPost(e) {
 if(e.target.dataset.role === 'submit-post') {
   // I did 2 requests as the same time. That was the problem
   http.submitPost();
   getPosts();
}

 e.preventDefault();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多