【问题标题】:Adding an Array to a JSON Object and sending it to server [duplicate]将数组添加到 JSON 对象并将其发送到服务器 [重复]
【发布时间】:2020-05-01 12:50:26
【问题描述】:

我在.json 文件中有一个对象,它只包含一个数组。

现在我想用prompt从用户那里得到一个词,并将它添加到这个数组中;你可以看到下面的代码:

function addWord() {
    let myWords = getWords();
    let newWord = prompt("What word would you like to be added to your list?", "");
    myWords.push(newWord);
    let myWordsJson = JSON.stringify(myWords);
    let xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "words.json?wordsArray=" + myWordsJson);
    xhr2.send();
}

这里是getWords()函数:

function getWords() {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "words.json", false);
    xhr.send();
    let myCode = JSON.parse(xhr.responseText);
    return myCode["wordsArray"];
}

我已经调试了我的代码,从服务器接收数组并添加新单词没有问题,但是我无法将新数组发送到words.json文件。

这里是words.json

{"wordsArray" : ["hello", "pencil", "school", "tooth", "family", "class"]}

【问题讨论】:

  • 无法将新数组发送到文件是什么意思?您是否拥有处理这些请求的后端?它对您的 GET 请求有什么作用?
  • 您是否尝试使用简单的 GET 请求编辑服务器上的文件?如果服务器不为您提供编辑此类文件的功能,则不可能
  • 我该如何处理? WebApi 是个不错的选择吗?

标签: javascript json


【解决方案1】:

我们必须将单个单词压入数组

 let newWord = "What word would you like to be added to your list?";
 myWords['wordsArray'].push(newWord);

或者如果我们要推送另一个单词数组,我们可以使用 for 循环,如下所示

 let newWord = ["What word would you like to be added to your list?"];
         
      for(let i = 0; i < newWord.length ; i++) {   
         myWords['wordsArray'].push(newWord[i]);
         }

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    相关资源
    最近更新 更多