JSON数据未显示在网页上

时间:2018-12-07 05:04:10

标签: jquery json

我正在尝试-第一次-连接到Blackbaud API,检索JSON对象,并将其显示在网页上。我正在使用的request.open链接(以下未显示,因为它包含用户数据)在将其直接放入浏览器时返回的信息没有错误。

以下是JSON数据返回的示例:

{"getConsTransactionsResponse":{"transaction":{"amount":{"formatted":"$50.00","decimal":"50.00"},"timestamp":"2016-02-01T09:43:54.458-06:00","pay_method":"ONLINE","billing_name":{"title":null,"last":"Smith","suffix":null,"middle":null,"first":"John","prof_suffix":null},"transaction_type":"DONATION","tender_type":"INVALID","confirmation_code":{},"donation_detail":{"value_of_goods":{"formatted":"$0.00","decimal":"0.00"},"tax_deductible_amount":{"formatted":"$0.00","decimal":"0.00"},"level":{"id":"9921","title":"API Donation Level"},"form":{"id":"9999","title":"API Form","description":"Sample form for API documentation."},"campaign":{"id":"9901","title":"API Campaign","description":"Sample campaign for API documentation."}},"billing_address":{"street2":null,"zip":null,"street1":null,"county":null,"state":null,"street3":null,"country":null,"city":null}}}}

我用来检索然后显示数据的脚本在这里:

<script type="text/javascript">
$(document).ready(function() {
    "use strict";

    var donHistory = "";
    var request = new XMLHttpRequest();
    request.open('GET', 'JSON LINK', true);
    request.onload = function () {
        // begin accessing JSON data here
        var data = JSON.parse(this.response);
        donHistory += '<div>';
        for (var i=0; i<data.length; i++) {
            donHistory += data[i].transaction.amount + '<br>';
        }
        donHistory += '</div>';         
        var divHistory = document.createElement("div");
        var divHistoryText = document.createTextNode(donHistory); 
        divHistory.appendChild(divHistoryText);
        var divElement = document.getElementById("col-content-box");
        divElement.appendChild(divHistory);
    };      
    request.send();
});

我的网页上显示的只是一个开始和结束div。

它放置在正确的区域,没有JSON数据。控制台未显示任何错误。显然,我对此并不陌生,并且犯了一些简单的错误。

我需要帮助的是:

1)为什么我所知道的JSON数据没有进入屏幕?

2)如果/当我确实可以使用此功能时,将显示内容显示为文本而不是嵌入代码,这是在做错什么吗?

2 个答案:

答案 0 :(得分:1)

检查控制台(按F12键),您可能会看到错误“未定义响应”。如果是这样,则必须在“ onload”功能上放置“ response”变量,如下所示:

request.onload = function (response) {

答案 1 :(得分:0)

请查看以下片段,该片段类似于您最近的屏幕截图中的代码。您应该可以在此站点上的此处运行摘要,以查看它是否有效。我改变了一些地方:

  • 我将AJAX调用与使用renderTransactions生成HTML以便显示的代码进行了分离
  • 出于演示目的,我使用renderTransactions显示了自己的一些测试数据
  • 我写了renderTransactions来使用称为Template Literals的ES2015功能,该功能使我可以简洁地将数据值与HTML合并
  • 我将您的数据呈现到了一个表(使用引导程序样式化)中。我对<table>的选择是任意的;您可以使用任何想要的HTML元素。

希望您能看到如何扩展我从这里开始的应用程序。  片段中有一条注释,描述了如何重新连接AJAX呼叫,出于演示目的,我已禁用它。

祝你好运!

$(document).ready(function() {

  /* Since I do not have access to your HTTP endpoint, 
   ** I've used my own test data that resembles your data.
   ** When you're ready to run this code against your endpoint,
   ** remove the block up to and including the `return` statement.
   */

  renderTransactions([
    {amount: {formatted: '$1.00'},credit_card_type: 'VISA'},
    {amount: {formatted: '$2.00'},credit_card_type: 'MASTERCARD'},
    {amount: {formatted: '$3.00'},credit_card_type: 'MASTERCARD'},
    {amount: {formatted: '$4.00'},credit_card_type: 'MASTERCARD'},
    {amount: {formatted: '$5.00'},credit_card_type: 'VISA'}
  ]);

  return;

  $.ajax({
    dataType: 'json',
    url: 'INSERT YOUR URL HERE',
    method: 'GET',
    /* I think this should be GET but in your screenshot it appeared that you had something much longer here, not sure why. */
    success: function(data) {
      renderTransactions(data.getConsTransactionsResponse.transaction);
    }
  });
});

function renderTransactions(transactions) {
  let $transactionTable = $(`
    <table class="table table-bordered table-sm">
      <thead>
        <tr>
          <th>Amount</th>
          <th>Credit Card Type</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>`).appendTo('#col-content-box');

  let $transactionTableBody = $transactionTable.find('tbody');

  transactions.forEach(t => {
    $transactionTableBody.append($(`
      <tr>
        <td>${t.amount.formatted}</td>
        <td>${t.credit_card_type}</td>
      </tr>
    `));
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<div id="col-content-box"></div>