首页 > 解决方案 > 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
    }
};

标签: javascript

解决方案


正如我在评论中提到的(也是@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>


推荐阅读