MVC JavaScript获取API数据并发送到控制器

2fjabf4q  于 2023-08-02  发布在  Java
关注(0)|答案(1)|浏览(88)

如何使用MVC获取API数据并将其发送到控制器?
以下是我到目前为止所做的:

"use strict";

const appData = (() => {
  return {
    fetchJSON: url => {
      fetch(url).then(response => {
        if (response.status !== 200) {
          console.log(response.status);
          return;
        }
        response.json().then(data => {
          console.log(data);
          //Send data to controller
        });
      });
    }
  };
})();

const appUI = (() => {
  
  return {
  };
})();

const appController = ((appData, appUI) => {
  //Get data from appData.fetchJSON()

  return {
    init: () => {
      console.log("Application Initialized...");
      appData.fetchJSON("./data.json");
    }
  };
})(appData, appUI);

appController.init();

字符串
这个想法是使用来自API的数据来填充前端的一些元素。

rdlzhqv9

rdlzhqv91#

您可以使用async函数发出请求,然后返回结果数据。在init函数中,您可以await调用fetchJSON函数的结果,然后可以将该数据传递给appUI

编辑

要在单击按钮时填充视图,您可以将数据存储在appData中,当单击按钮时,您可以从appData获取数据并填充视图。
参见下面的示例

const appData = (() => {
  const dataStore = {};
  
  const fetchJSON = async (url) => {
    try {
        let response = await fetch(url);
        return await response.json();
      } catch (error) {
        console.log(error);
      }
  };
  
  return { dataStore, fetchJSON };
})();

const appUI = ((appData) => {
  const btn = document.getElementById('btn');
  
  btn.addEventListener('click', (e) => {
    populateViews(appData.dataStore.data);
  });
  
  const populateViews = (data) => {
    const body = document.getElementsByTagName('body')[0];
    const post = `
        <div>
          <p><strong>Post ID:</strong> ${data.id}</p>
          <p><strong>Title</strong></p>
          <p>${data.title}</p>
          <p><strong>Body</strong></p>
          <p>${data.body}</p>
        </div>
    `;
    body.insertAdjacentHTML('beforeend', post);
  };
  
  return { btn };
})(appData);

const appController = ((appData, appUI) => {
  const init = async () => {
      console.log("Application Initialized...");
      const data = await appData.fetchJSON('https://jsonplaceholder.typicode.com/posts/1');
      appData.dataStore.data = data;
      
      // enable button after data has been saved
      appUI.btn.removeAttribute('disabled');
  };
  
  return { init };
})(appData, appUI);

appController.init();
button {
  padding: 12px 15px;
  background: blueviolet;
  color: #fff;
  border-radius: 4px;
  outline: none;
  box-shadow: 0.1px 0.1px 3px rgba(0, 0, 0, 0.7);
  border: none;
  cursor: pointer;
}

button:disabled {
  background: #999;
  pointer-events: none;
}

div {
  margin-top: 15px;
}

p {
  margin: 5px 0;
}
<button id="btn" disabled>Fetch Data</button>

相关问题