javascript - 从 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")
})
}
}
解决方案
我认为你的代码是正确的。它只是缺少“成功”上的“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")
})
}
}
推荐阅读
- android - 以Horizontal Recyclerview为行文件实现Verticle Recyclerview
- c++ - C++ 模板:VS2017 中的 C2143 错误,但在 VS2013 中编译
- c# - .NET Core 2.2 time.ToString("d",culture) 异常
- python - 从数据库中将元素添加到 python 中的数据框列内的列表
- python - Tkinter Tic Tac Toe 在某个框中绘制形状
- typeerror - python生成器中的TypeError
- c# - 如何将数组值列表写入文本文件(文件名列表)
- collections - Hyperledger 1.4.4:未清除私有数据
- python - 如何在不更改默认值的情况下在当前目录中启动 Jupyter Lab?
- laravel - 分离无效的令牌响应