JSON APIs 和 AJAX - 使用 JavaScript 的 fetch 方法获取 JSON

告诉我们发生了什么:
一个小细节!
使用fetch()方法和使用XMLHttpRequest不同的是,在最后的插入请求返回的 JSON 对象创建的字符串修改元素的 HTML 代码时,这里使用了data而XMLHttpRequest使用了json,想知道为什么?

你目前的代码

<script>
  document.addEventListener('DOMContentLoaded',function(){
    document.getElementById('getMessage').onclick= () => {
      // 在这行下面添加代码
fetch('/json/cats.json')//发起请求fetch(URL)向指定的URL发起GET请求,返回一个Promise
.then(response=>response.json())//请求成功执行then方法转化成json格式
.then(data=>{//传入JSON对象
  document.getElementByID('message').innerHTML=JSON.stringify(data);//插入请求返回的 JSON 对象创建的字符串修改元素的 HTML 代码。


})

      // 在这行上面添加代码
    };
  });
</script>
<style>
  body {
    text-align: center;
    font-family: "Helvetica", sans-serif;
  }
  h1 {
    font-size: 2em;
    font-weight: bold;
  }
  .box {
    border-radius: 5px;
    background-color: #eee;
    padding: 20px 5px;
  }
  button {
    color: white;
    background-color: #4791d0;
    border-radius: 5px;
    border: 1px solid #4791d0;
    padding: 5px 10px 8px 10px;
  }
  button:hover {
    background-color: #0F5897;
    border: 1px solid #0F5897;
  }
</style>
<h1>Cat Photo Finder</h1>
<p id="message" class="box">
  The message will go here
</p>
<p>
  <button id="getMessage">
    Get Message
  </button>
</p>

你的浏览器信息:

用户代理是: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36

挑战: JSON APIs 和 AJAX - 使用 JavaScript 的 fetch 方法获取 JSON

挑战的链接:

They are both just variable names (one is a normal variable the other a parameter).

There is no reason why they can’t be named the same for both methods. There aren’t really any naming rules. It can be data or json, or cats for that matter (seeing as it is fetching a list of cats).

遇到了什么问题? 有什么困惑 ? 麻烦提供一下。

got it! thx
I changed data to json ,it still worked :grinning:

只是变量名的问题~已经明白了~感谢 :smiley: :smiley: :smiley: