Невозможно получить значение от JSON до Javascript - PullRequest
0 голосов
/ 16 февраля 2020

Я пытаюсь загрузить значение JSON, которое хранится в Google Sheet, на мою страницу HTML.

В настоящее время я разочарован тем, как получить значение "12345678" который находится под "gsx $ date" и "$ t".

Однако я не могу получить значение Speci c, и был получен только текст "} //]]>".

Может кто-нибудь помочь мне, пожалуйста? Спасибо!

Для части HTML я набрал следующий код для отображения указанных c json данных:

<table id="dataTable">
  <tbody>

  </tbody>
</table>

Для Javascript части:

<script type="text/javascript" language="javascript>
let xhr = new XMLHttpRequest;
xhr.open('GET', 'url', true);
xhr.onload = function() 
{
  if (this.status === 200) 
  {
    let data = JSON.parse(this.responseText).entry,
            tbodyHtml = '';

    data.map(function(d) {
        tbodyHtml =+ `
        <tr>
            <td>${d.gsx$date.$t}</td>
        </tr>
      `;
    });

    document.querySelector('#dataTable tbody').innerHTML = tbodyHtml;
  }
}
xhr.send();
</script>

Это мои JSON данные из Google Sheet

    { 
   "version":"1.0",
   "encoding":"UTF-8",
   "feed":{ 
      "xmlns":"http://www.w3.org/2005/Atom",
      "xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/",
      "xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended"
      },
      "updated":{ 
         "$t":"2020-02-16T06:28:44.692Z"
      },
      "category":[ 
         { 
            "scheme":"http://schemas.google.com/spreadsheets/2006",
            "term":"http://schemas.google.com/spreadsheets/2006#list"
         }
      ],
      "title":{ 
         "type":"text",
         "$t":"Today"
      },
      "openSearch$totalResults":{ 
         "$t":"1"
      },
      "openSearch$startIndex":{ 
         "$t":"1"
      },
      "entry":[ 
         { 
            "updated":{ 
               "$t":"2020-02-16T06:28:44.692Z"
            },
            "category":[ 
               { 
                  "scheme":"http://schemas.google.com/spreadsheets/2006",
                  "term":"http://schemas.google.com/spreadsheets/2006#list"
               }
            ],
            "title":{ 
               "type":"text",
               "$t":"1"
            },
            "content":{ 
               "type":"text",
               "$t":"time: 2, todayhightemp: 3, todayhightemptime: 4"
            },
            "link":[ 
               { 
                  "rel":"self",
                  "type":"application/atom+xml",
                  "href":"https://spreadsheets.google.com/feeds/list/133WezZS498sLEDZ-2ZM_2lvxwcMYwXTiGZPBC0Do0p8/od6/public/full/cokwr"
               }
            ],
            "gsx$date":{
               "$t":"12345678"
            },
            "gsx$time":{ 
               "$t":"23456789"
            },
            "gsx$todayhightemp":{ 
               "$t":"34567890"
            },
            "gsx$todayhightemptime":{ 
               "$t":"45678901"
            },
            "gsx$todaylowtemp":{ 
               "$t":""
            },
            "gsx$todaylowtemptime":{ 
               "$t":""
            },
            "gsx$todayhighrh":{ 
               "$t":""
            },
            "gsx$todayhighrhtime":{ 
               "$t":""
            },
            "gsx$todaylowrh":{ 
               "$t":""
            },
            "gsx$todaylowrhtime":{ 
               "$t":""
            },
            "gsx$todayhighbar":{ 
               "$t":""
            },
            "gsx$todayhighbartime":{ 
               "$t":""
            },
            "gsx$todaylowbar":{ 
               "$t":""
            },
            "gsx$todaylowbartime":{ 
               "$t":""
            },
            "gsx$todayhighwindspeed":{ 
               "$t":""
            },
            "gsx$todayhighwindspeedtime":{ 
               "$t":""
            },
            "gsx$todayrainrate":{ 
               "$t":""
            },
            "gsx$todayhighrainrate":{ 
               "$t":""
            },
            "gsx$todayhighrainratetime":{ 
               "$t":""
            },
            "gsx$todayet":{ 
               "$t":""
            },
            "gsx$todayhighsolarradiation":{ 
               "$t":""
            },
            "gsx$todayhighsolarradationtime":{ 
               "$t":""
            },
            "gsx$todayhighuv":{ 
               "$t":""
            },
            "gsx$todayhighuvtime":{ 
               "$t":""
            },
            "gsx$todayhighdewpoint":{ 
               "$t":""
            },
            "gsx$todayhighdewpointtime":{ 
               "$t":""
            },
            "gsx$todaylowdewpoint":{ 
               "$t":""
            },
            "gsx$todaylowdewpointtime":{ 
               "$t":""
            },
            "gsx$todayhighheatindex":{ 
               "$t":""
            },
            "gsx$todayhighheatindextime":{ 
               "$t":""
            }
         }
      ]
   }
}

1 Ответ

0 голосов
/ 16 февраля 2020

1) Загрузить все как JSON. Поэтому для достижения этого, пожалуйста, следуйте этому руководству, чтобы получить весь лист как JSON. Когда я следовал этому уроку, мой GOOGLESHEETCODE был кодом, сгенерированным из кнопки общего доступа в верхнем правом углу.

2) Используйте fetch или axe ios для выполнения запроса.

Вот пример с fetch:

const url = 'YOUJSONENDPOINTURL';


fetch(url)
    .then(data=> data.json())
    .then(result => {
        let firstCell = result['feed']['entry'][0]['gsx$date']['$t'];

        result['feed']['entry'].forEach((b) => { // loop through all cells
           console.log(b.gsx$date.$t);
        })
    })

Вы можете использовать XMLHttpRequest как это по вашему запросу. Проблема в вашем примере заключается в том, что прикрепленный вами JSON недействителен, и это не та структура JSON, которую мы извлекаем из листов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...