javascript - JavaScript AJAX:获取两个对象作为响应
问题描述
我有一个带有两个div 的 HTML 页面:
<div id = "first_div">some initial stuff here</div>
<div id = "second_div">another stuff here</div>
我有一个发送请求的 JavaScript AJAX 函数。响应返回一个包含两个对象的页面,例如段落:
<p id = "first_paragraph">contents of the first paragraph</p>
<p id = "second_paragraph">contents of the second paragraph</p>
如何调整我的脚本以实现将响应中的first_paragraph插入到first_div中,并将响应中的second_paragraph插入到second_div中?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("first_div").innerHTML = //put here the first paragraph from the response;
document.getElementById("second_div").innerHTML = //put here the second paragraph from the response
}
};
解决方案
正如我在评论中提到的(也是@Endless 推荐的),您可以使用fetch API。
在以下示例中,我将收到来自jsonplaceholder的响应,因为我不知道您使用的来源。
示例 #1(获取文本):
const fetchData = async() => (await fetch('https://jsonplaceholder.typicode.com/todos/1')).text();
fetchData()
.then(data => {
first_div.innerHTML = data;
second_div.innerHTML = data;
});
<div id="first_div">some initial stuff here</div>
<div id="second_div">another stuff here</div>
示例 #2(获取 JSON):
const fetchData = async() => (await fetch('https://jsonplaceholder.typicode.com/todos/1')).json();
fetchData()
.then(data => {
first_div.innerHTML = data.id;
second_div.innerHTML = data.title;
});
<div id="first_div">some initial stuff here</div>
<div id="second_div">another stuff here</div>
推荐阅读
- php - 在 wordpress 中使用函数更新字段
- matrix - 平均上下三角矩阵
- ember.js - 在启动 ember 服务器时,我收到了类似 SyntaxError: Unexpected identifier async postBuild() 之类的错误
- node.js - 为什么通过刷新浏览器 bundle_client 上的页面 localhost 会停留在待处理状态?
- docker - Docker - 如何列出卷名称 - 简单的方法
- c++ - 如何为不同的类声明相同的对象名称?
- python - pylibjpeg-libjpeg 未安装
- c# - SignalR with .NET 5 是否与运行 .NET Standard 2.1 的 Blazor 应用程序兼容?
- c++ - 在 CMake 中安装静态库的调试和发布配置
- xml - 将一个大 XML 分解为多个 tf 资源