如何 select 使用 XMLHttpRequest 检索特定变量

How to select specific Variables retrieved using XMLHttpRequest

我正在尝试在我的网站上进行整合。我已使用 XMLHttpRequest 成功检索数据,但是我不需要所有信息我只需要特定信息。

这是我的JavaScript代码
`

使用 XMLHttpRequest 对象

 <div id="demo">
 <button type="button" onclick="loadXMLDoc()">Change Content</button>
 </div>

 <script>

 function loadXMLDoc() {
 var url = "https://api.paystack.co/transaction/";

 var xhr = new XMLHttpRequest();
 xhr.onreadystatechange = function() {
 if (xhr.readyState == 4 ) {
  document.getElementById("demo").innerHTML =
  xhr.responseText;
  console.log(xhr.responseText);
   
 }
};

 xhr.open("GET", url);

  xhr.setRequestHeader("Authorization", "Bearer secret key");

 xhr.send();

}
 </script>

`

这是控制台上的响应,不是全部,只显示一部分

{ 
"status": true, 
"message": "Transactions retrieved", 
"data": [ 
    { 
        "id": 1806822806, 
        "domain": "test", 
        "status": "abandoned", 
        "reference": "773768164", 
        "amount": 56050, 
        "message": null, 
        "gateway_response": "The transaction was not completed", 
        "paid_at": null, 
        "created_at": "2022-05-09T12:17:25.000Z", 
        "channel": "card", 
        "currency": "NGN", 
        "ip_address": "197.210.55.168", 
        "metadata": 
            { 
                "customer": 
                    { 
                        "id": 79455936, 
                        "first_name": "", 
                        "last_name": "", 
                        "email": "sdfeferw@lkkil.com", 
                        "phone": "", 
                        "metadata": null, 
                        "customer_code": "CUS_xxxxxx", 
                        "risk_action": "default" 
                    }, 
                    
                        
            },

我需要的信息是

  1. 创建日期
  2. 名字
  3. 姓氏
  4. 数量

我想在 DIV 上显示它们,请问我该怎么做

xhr.responseText 是一个 JSON 字符串。您需要将其解析为 JS 对象,并且 select 只需要属性。喜欢

const jsonResponse = JSON.parse(xhr.responseText);
const { metadata, amount, created_at } = jsonResponse.data;
const { first_name, last_name } = metadata.customer;
const result = { first_name, last_name, created_at, amount };
document.getElementById("demo").innerHTML = JSON.stringify(result);