显示来自GitHub的JSON JavaScript对象到HTML。

huangapple go评论68阅读模式
英文:

Displaying JSON Javascript object from Github to HTML

问题

以下是代码部分的翻译:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>json</title>
    <script>
        function populateHeader(company) {
            const myH1 = document.createElement('h1');
            myH1.textContent = company['companyName'];
            header.appendChild(myH1);

            const myPara = document.createElement('p');
            myPara.textContent = 'Division: ' + company['division'] + ', ' + company['location'] + '\nHead: ' + company['divisionHeadName'];

            header.appendChild(myPara);
        }

        function showEmp(company) {
            const emps = company['members'];

            for (let i = 0; i < emps.length; i++) {
                const myArticle = document.createElement('article');
                const myH2 = document.createElement('h2');
                const myPara1 = document.createElement('p');
                const myList = document.createElement('ul');

                myH2.textContent = emps[i].name + ', ' + emps[i].gender;
                myPara1.textContent = 'Age: ' + emps[i].age + ", Favorite Fruit: " + emps[i].favoriteFruit + ", Contacts:";

                const contacts = emps[i].contacts;
                for (let j = 0; j < contacts.length; j++) {
                    const listItem = document.createElement('li');
                    listItem.textContent = emps[j].name + ", " + emps[j].company;
                    myList.appendChild(listItem);
                }

                myArticle.appendChild(myH2);
                myArticle.appendChild(myPara1);
                myList.appendChild(listItem);

                section.appendChild(myArticle);
            }
        }
        
    </script>
</head>
<body>
    <header id="hdr">
    </header>

    <section id="sct">
    </section>

    <script>
        const header = document.querySelector('header');
        const section = document.querySelector('section');

        let requestURL = 'https://github.com/drgap/json_example/blob/main/company.json';
        let request = new XMLHttpRequest();
        request.open('GET', requestURL);
        request.responseType = 'json';
        request.send();

        request.onload = function () {
            const company = request.response;
            populateHeader(company);
            showEmp(company);
        }

        header = header.toString();
        section = section.toString();
        document.getElementById("hdr").innerHTML = JSON.stringify(header);
        document.getElementById("sct").innerHTML = JSON.stringify(section);
    </script>
</body>
</html>

希望这有助于您的工作。如果您需要任何其他帮助,请随时告诉我。

英文:

I'm pulling JSON from GitHub, turning it into a JS object, and displaying it to HTML. So far I have the first two parts, but I cannot figure out how to display it. Lines 70-73 are my current attempt.

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot; /&gt;
&lt;title&gt;json&lt;/title&gt;
&lt;script&gt;
function populateHeader(company) {
const myH1 = document.createElement(&#39;h1&#39;);
myH1.textContent = company[&#39;companyName&#39;];
header.appendChild(myH1);
const myPara = document.createElement(&#39;p&#39;);
myPara.textContent = &#39;Division: &#39; + company[&#39;division&#39;] + &#39;, &#39; + company[&#39;location&#39;] + &#39;\nHead: &#39; + company[&#39;divisionHeadName&#39;];
header.appendChild(myPara);
}
function showEmp(company) {
const emps = company[&#39;members&#39;];
for (let i = 0; i &lt; emps.length; i++) {
const myArticle = document.createElement(&#39;article&#39;);
const myH2 = document.createElement(&#39;h2&#39;);
const myPara1 = document.createElement(&#39;p&#39;);
const myList = document.createElement(&#39;ul&#39;);
myH2.textContent = emps[i].name + &#39;, &#39; + emps[i].gender;
myPara1.textContent = &#39;Age: &#39; + emps[i].age + &quot;, Favorite Fruit: &quot; + emps[i].favoriteFruit + &quot;, Contacts:&quot;;
const contacts = emps[i].contacts;
for (let j = 0; j &lt; contacts.length; j++) {
const listItem = document.createElement(&#39;li&#39;);
listItem.textContent = emps[j].name + &quot;, &quot; + emps[j].company;
myList.appendChild(listItem);
}
myArticle.appendChild(myH2);
myArticle.appendChild(myPara1);
myList.appendChild(listItem);
section.appendChild(myArticle);
}
}
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;header id=&quot;hdr&quot;&gt;
&lt;/header&gt;
&lt;section id=&quot;sct&quot;&gt;
&lt;/section&gt;
&lt;script&gt;
const header = document.querySelector(&#39;header&#39;);
const section = document.querySelector(&#39;section&#39;);
let requestURL = &#39;https://github.com/drgap/json_example/blob/main/company.jsonhttps://github.com/drgap/json_example/blob/af5d92bc9ed1b399aabdc50b132f51324025facd/company.json&#39;;
let request = new XMLHttpRequest();
request.open(&#39;GET&#39;, requestURL);
request.responseType = &#39;json&#39;;
request.send();
request.onload = function () {
const company = request.response;
populateHeader(company);
showEmp(company);
}
header = header.toString();
section = section.toString();
document.getElementById(&quot;hdr&quot;).innerHTML = JSON.stringify(header);
document.getElementById(&quot;sct&quot;).innerHTML = JSON.stringify(section);
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

Tried JSON.stringify on multiple objects to attempt to get it to display. Expected to get full display of JSON in HTML page. Received blank page or "null".

答案1

得分: 1

以下是您要翻译的内容:

第一个问题:

Uncaught TypeError: Assignment to constant variable.
这告诉我们,header = header.toString() 这一行是错误的。正如错误消息所指出的,header 是一个常量,因此其值不能被更新。section 也一样。您可以通过使用以下方式声明 header 来修复这个问题:

let header = document.querySelector('header');

第二个问题:

Access to XMLHttpRequest at
'https://github.com/drgap/json_example/blob/af5d92bc9ed1b399aabdc50b132f51324025facd/company.json'
from origin 'null' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
这是一个CORS错误。简短解释一下,由于GitHub在其服务器上设置资源的方式,您无法从不同的网站获取它们,因为域名不同。您可能是从localhost发出请求,因此出现了错误。我强烈建议深入研究CORS,对于初学者来说并不直观,深入理解这个主题将为您节省很多时间和精力。幸运的是,您可以通过以下方式解决此问题。

第三个问题:URL没有提供JSON内容,而是一个显示JSON内容的页面。打开您正在使用的URL,您会注意到它会将您带到一个完整的网页,而不仅仅是JSON内容。正如评论中的某人所指出的,您可以使用原始资源获取文件的实际内容。替换原始URL,看看它如何修复问题。

第四个问题:

Uncaught TypeError: header.appendChild is not a function
为了理解这一点,您必须清楚JS如何执行代码。您有一个XMLHttpRequest以及对其send成员的调用。关键在于send是异步的。想象一下:您的代码有很多事情要做,它发送了一个请求到一个可能需要一秒钟才能生成响应的外部网站。JS为什么要等待响应呢?实际上它不需要,发送请求后,它继续执行代码,以避免浪费时间等待响应。这意味着在接收到请求的响应之前,会执行header = header.toString() 这一行。因此,在您调用 populateHeader 并执行 header.appendChild 时,header 变量已经是一个字符串。显然,字符串没有名为appendChild的成员,它是一个函数。我们如何修复这个问题?我真的鼓励您研究JS中的异步操作。同时,您可以将最后四行代码放在请求回调中(即request.onload块)。

下一个第五个问题:

Uncaught ReferenceError: listItem is not defined
listItem 仅在 showEmp 函数的for循环内定义。当您在循环内定义变量时,它只存在于循环内,而不会在循环外存在。因此,JS不知道在for之外的地方什么是listItem,因此出现了错误。

第六个问题:

Uncaught TypeError: Cannot read properties of undefined (reading 'name')
查看抛出此错误的那一行,您会发现您在emps[j],而一开始您使用的是emps[i]。我假设这只是一个疏忽。

在解决所有这些问题后,控制台将不再显示任何错误,但我猜页面仍然不会如您想象的那样显示。它只显示两个字符串“[object HTMLElement]”。您能猜到原因吗?

我不会提供完整的工作代码。逐个解决每个错误并理解发生了什么对于您来说将更有用。祝您好运和玩得开心!

英文:

There are a few issues in the code. When something does not work as expected in an HTML page, I suggest opening the console in Chrome to read through the errors, which are printed in red, and will give you detailed information about what's wrong.

First issue:

> Uncaught TypeError: Assignment to constant variable.

This is telling that the line header = header.toString() is wrong. As the error message points out, header is a constant and therefore its value cannot be updated. Same goes for section. You can fix this by declaring header with

let header = document.querySelector(&#39;header&#39;);

Second issue:

> Access to XMLHttpRequest at
> 'https://github.com/drgap/json_example/blob/af5d92bc9ed1b399aabdc50b132f51324025facd/company.json'
> from origin 'null' has been blocked by CORS policy: No
> 'Access-Control-Allow-Origin' header is present on the requested
> resource.

This is a CORS error. Short explanation, because of the way GitHub set up the resources on their servers you cannot fetch them from a different website, because the domain is different. You're probably making the request from localhost, therefore the error. I strongly suggest to research into CORS, it's not very intuitive for begginers and a thorough understanding of that topic will save you a lot of swear words and effort in the future. Luckily you can get around this issue with the next point.

Third issue: the URL does not provide JSON content, but a page with a sections that shows JSON content. Open the URL you're using and you will notice that it takes you to a full blown web page, not just JSON content. As someone pointed out in comments, you can get the actual content of the file using the raw resource. Replace the raw URL and see how it fixes the problem.

Fourth issue:

> Uncaught TypeError: header.appendChild is not a function

In order to understand this point, you must have clear in mind how JS executes code. You have an XMLHttpRequest along with a call to its send member. The key here is that send is asynchronous. Imagine: your code has tons of things to do and it sends out a request to an external website that will take maybe a second to generate a response. Why on earth would JS need to wait for the response? In fact it doesn't, after sending the request it goes on executing the code to avoid wasting time in the second waiting for the response. This means that the line header = header.toString() is executed before the response of the request is received. Therefore, by the time you call populateHeader and do header.appendChild, the header variable will already be a string. A string clearly doesn't have a member called appendChild which is a function. How do we fix this? I really encourage to look into asynchronous operations in JS. In the meanwhile, you can just put the last four lines inside the request call back (i.e., the request.onload block).

Next and fifth issue:

> Uncaught ReferenceError: listItem is not defined

listItem is only defined inside a for loop of the showEmp function. When you define a variable inside a loop, it exists within the loop and not anywhere else. Therefore, JS doesn't know what listItem is outside the for. But you're still refer to it, hence the error.

Sixth:

> Uncaught TypeError: Cannot read properties of undefined (reading
> 'name')

Take a look at the line where this error is thrown and you'll find out that you're doing emps[j], whereas at the beginning you were doing emps[i]. I assume this is just an oversight.

After we fix all of this, the console is going to be clean without any errors, but I guess the page is still not looking as you imagined it would. It just shows two strings &quot;[object HTMLElement]&quot;. Can you guess why?

I will not provide the full working code to this. It's much, much more useful for you to go through all of these errors one by one and understand what's happening for each and every of them. Have fun and good luck with this!

huangapple
  • 本文由 发表于 2023年2月19日 04:34:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定