如何向服务器发送和从服务器接收 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.