首页 > 解决方案 > 从 db.json 文件中检索数据并使用 javascript 将其添加到数组中

问题描述

我在游戏中使用 ajax 和 javascript,并使用 json-server 创建了一个服务器,我在其中保存了一个 db.json 文件,其中包含用户可以输入并在游戏中可用的单词。

db.json

这是json文件的样子

{
  "words": [
    {
      "cuvant": "cuvant",
      "id": 1
    },
    {
      "cuvant": "masina",
      "id": 2
    },
    {
      "cuvant": "oaie",
      "id": 3
    },
    {
      "cuvant": "carte",
      "id": 4
    },
    {
      "cuvant": "fmi",
      "id": 5
    },
    {
      "cuvant": "birou",
      "id": 6
    },
    {
      "cuvant": "birou",
      "id": 7
    },
    {
      "cuvant": "canapea",
      "id": 8
    },
    {
      "cuvant": "pasare",
      "id": 9

我设法使用以下方法获取 POST 请求(将单词添加到 db.json):

    function addWord() {
  var word = document.getElementById("input-name").value;
  var info = {
    cuvant: word
  }

  $.ajax({
    url:'http://localhost:3000/words',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(info),
    succes: function(info) {
      console.log(info)
    },
    error: function(error) {
      console.log(error);
    }
  })
}

这是我为 GET 请求尝试的

但我不确定它是否正确。而且我还需要一种方法来仅获取cuvant键持有的并将其添加到数组中。

window.onload = function() {
  function gett() {
    $.ajax({
      url: 'http://localhost:3000/words',
      type: 'GET',
      dataType: 'json',
      contentType: "application/json",
      succes: function(data) {
        console.log(data);
      },

      error: function(data) {
        console.log(data)
      }
    })

    .done(function(){
      console.log("Over")
    })
  }
}

标签: javascripthtmljsonajax

解决方案


我认为你的代码是正确的。它只是缺少“成功”上的“s”:

window.onload = function() {
  function gett() {
    $.ajax({
      url: 'http://localhost:3000/words',
      type: 'GET',
      dataType: 'json',
      success: function(data) {
        console.log(data);
      },
      error: function(data) {
        console.log(data)
      }
    })
    .done(function(){
      console.log("Over")
    })
  }
}

推荐阅读