如何向伺服器傳送和從伺服器接收 JSON 資料


JavaScript 可以向伺服器傳送網路請求,並載入 JSON。JS 利用一種名為 AJAX 的技術來實現此操作。AJAX 代表非同步 JavaScript 和 XML。JS 有一個 API(即獲取)來獲取(接收)資訊,並向伺服器釋出(傳送)資訊。

你可以使用 fetch 以以下方式獲取 JSON 資料 −

範例

const URL = 'https://jsonplaceholder.typicode.com/todos/1'
// Send a GET request without any data to the server
fetch(URL, {method: "GET"})
// Get the JSON data from the raw response
   .then(res => res.json())
// Print the result
   .then(console.log)

輸出

這將給出以下輸出 −

{
   "userId": 1,
   "id": 1,
   "title": "delectus aut autem",
   "completed": false
}

你還可以使用 fetch 向伺服器釋出資料。例如,要建立上述伺服器上的一個新待辦事項,你可以釋出你自己的資料 −

範例

const URL = 'https://jsonplaceholder.typicode.com/todos'
const data = {
   "userId": 1,
   "title": "delectus aut autem",
   "completed": false
};
// Send a post request
fetch(URL, {
   method: "POST",
   body: JSON.stringify(data),
   headers: {
      "Content-type": "application/json; charset=UTF-8"
   }
})

這將在佔位符 API 上建立一個待辦事項。

更新於:27-11-2019

3000+ 次瀏覽

開啟你的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.