首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript来获取图像src和其他没有显示任何信息的信息

Javascript来获取图像src和其他没有显示任何信息的信息
EN

Stack Overflow用户
提问于 2022-10-23 05:22:13
回答 2查看 75关注 0票数 0

所以,就像标题说的,我编写了代码,从json加载信息,并在超级简单的HTML页面上显示它。我想要的是它显示图像,标题和有一个按钮来加载一个新的图像。问题是只有按钮才会出现。

我在这里错过了什么?

Javascript

代码语言:javascript
复制
// function to output the image to the page with the title and description
function output(comic_info) {
    let article = document.createElement("article");
    let h3 = document.createElement("h3");
    h3.innerHTML = comic_info.title;
    let img = document.createElement("img");
    img.src = comic_info.img;
    img.alt = comic_info.alt;
    article.appendChild(h3);
    article.appendChild(img);
    document.getElementById("comics").appendChild(article);
}

// fetch the info from the url about the comic
async function getComic(comic_url) {
    const response = await fetch(comic_url);
    // check that fetch is successful
    if (response.ok) {
        comic_info = await response.json();
        output(comic_info);
    }
}

// get a different comic's info
function getNewComic() {
    let random_number = Math.floor(Math.random() * 1000);
    let comic_url = "https://xkcd.com/" + random_number + "/info.0.json";
    getComic(comic_url);
}

// when a button is clicked, get a new comic
document.getElementById("new_comic").addEventListener("click", getNewComic);

代码语言:javascript
复制
<body>
    <main>
        <section>
            <!-- div to add comic image and info to the page -->
            <div id="comics">
            </div>

            <!-- button to choose new comic -->
            <button id="new_comic">New Comic</button>
        </section>
    </main>
    <footer>
        &copy;<span id="year"></span> | Project | Lesson 06
    </footer>
    <script src="/week06/student_files/scripts/main.js"></script>
    <script src="/week06/w06_project.js"></script>
</body>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-10-23 09:14:50

我看了你的密码。您所面临的问题是因为一种叫做CORS的东西。当然,您可以从网站访问数据,因为您正在使用他们自己的网站,服务器为您提供所需的数据。但是,当您试图从代码中获取相同的信息时,情况就不同了,因为您正在localhost上运行代码,服务器无法识别该代码。这就是为什么服务器阻止您的请求,而不发送任何东西。

代码语言:javascript
复制
if (response.ok) {
    comic_info = await response.json();
    output(comic_info);
  }

output函数永远不会被调用,因为response.ok不是true/truthy,因为服务器阻止了您的请求。你能做到的唯一方法就是

  1. 从浏览器中向同一个url发出大量请求,并将响应保存在json文件中,然后随机选择一个并输出特定的漫画。
  2. 或者你必须找到其他网站,允许跨源请求共享(CORS)。

希望这能帮上忙!

票数 1
EN

Stack Overflow用户

发布于 2022-10-23 06:18:22

看起来,单击按钮会触发getNewComic函数,该函数确实会生成一个有效的URL,然后成功地调用getComic函数。响应变量从未定义过,因为fetch似乎没有返回。在每个函数的开头删除带有附加变量的console.logs有助于跟踪事物停止工作的地方,例如:

代码语言:javascript
复制
async function getComic(comic_url) {
  console.log('In getComic', comic_url);

这将返回一个有效的URL到控制台,因此我们知道它有那么远,但是fetch似乎没有返回。如果在提取之后删除一个console.log,它就不会被调用。

您可以通过在浏览器中直接获取URL并将其分配给一个变量来模拟该对象,以便对项目的其余部分进行故障排除,然后在最后返回fetch。注释掉fetch,这样它就不会拖住函数,然后手动将有效的JSON分配给响应变量。

例如:

代码语言:javascript
复制
  // const response = await fetch(comic_url);
  const response = {
    month: '7',
    num: 1234,
    link: '',
    year: '2013',
    news: '',
    safe_title: 'Douglas Engelbart (1925-2013)',
    transcript:
      'San Francisco, December 9th, 1968: \n[[We see a figure talking into a headset. It\'s a fair assumption that it\'s Douglas Engelbart.]]\nDouglas: ... We generated video signals with a cathode ray tube... We have a pointing device we call a "mouse"... I can "copy" text... ... and we have powerful join file editing... underneath the file here we can exchange "direct messages"...\n\n[[Douglas continues to narrate. Some music is playing.]]\nDouglas: ... Users can share files... ... files which can encode audio samples, using our "masking codecs"... The file you\'re hearing now is one of my own compositions...\nMusic: I heard there was a secret chord\n\n[[Douglas continues to narrate.]]\nDouglas: ... And you can superimpose text on the picture of the cat, like so... This cat is saying "YOLO", which stands for "You Only Live Once"... ...Just a little acronym we thought up...\n\n{{Title text: Actual quote from The Demo: \'... an advantage of being online is that it keeps track of who you are and what you\u00e2\u0080\u0099re doing all the time ...\'}}',
    alt: "Actual quote from The Demo: '... an advantage of being online is that it keeps track of who you are and what you\u2019re doing all the time ...'",
    img: 'https://imgs.xkcd.com/comics/douglas_engelbart_1925_2013.png',
    title: 'Douglas Engelbart (1925-2013)',
    day: '5',
  };

  console.log(JSON.stringify(response));

完成项目的其余部分,看看是否可以让html构造部分处理您知道是有效的数据,然后返回到fetch。

xkcd可能显式禁止代码在未经许可的情况下获取数据,这将解释您正在获取的CORS错误。CORS是跨源资源共享,它是一种机制,用于确定谁可以访问由ip、端口、域等标识的服务器的资源,并专门防止某人未经许可从他人的服务器嵌入内容。如果是这样的话,除非您获得xkcd的许可(如果他们已经锁定了xkcd,这是不太可能的),那么您将希望为这个项目找到另一个内容源。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74168842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档