1.)我有一个功能,可以根据用户输入成功生成随机词(如果用户输入是10个,网站上会显示10个随机词)。如果我使用 GET request fetch api 获取单词,则有一个 json 服务器,如下所示:
function getRandomWords() {
let words = getServerData('http://localhost:3000/words').then(data => {
const wordsToMemorize = document.querySelector('#words-to-memorize');
document.querySelector("#wordsInput").addEventListener("click", function() {
let temp = wordsToMemorize.value;
generatedArrayELements.innerHTML = "";
for(let i = 0; i < temp; i++) {
let rander = Math.floor(Math.random() * 3000);
generatedArrayELements.innerHTML += data[rander] + "</br>";
}})
});
}
2.)我想将生成的单词转移到我的 .json 文件中,randomwords array但它不想工作。并且在那里使用 DOM 也没有意义,我刚刚意识到:
function putServerData() {
let data = getRandomWords();
let fetchOptions = {
method: "POST",
mode: "cors",
cache: "no-cache",
headers: {
'Content-Type': 'application/json'
},
credentials: "same-origin",
body: JSON.stringify(data)
};
return fetch("http://localhost:3000/randomwords", fetchOptions)
.then(resp => resp.json())
.then(json => console.log(json));
}
document.querySelector("#wordsInput").addEventListener("click", function() {
putServerData();
})
3.) 我觉得非常接近我的目标,因为随机词生成器可以工作,如果我手动将值设置为let data变量,我也可以将数据 POST 到 .json 文件中,比如let data = ["test"]. 我不知道如何将生成的随机单词发送到我的 .json 文件中。
4.) 我的 json 文件:
{
"randomwords": [],
"words": [
"a",
"abandon",
"ability",
"able",
"abortion",
"about",
"above",
"abroad",
"absence",
"absolute",
"absolutely",
"absorb",
"abuse",
"academic",
"accept",
"access"...(remaining words...)
}]
4.) 我尝试按照文档进行操作。也许我需要使用一些timeout,因为在我使用它们之前首先需要生成随机词POST request。我已经为此苦苦挣扎了将近一个星期,但找不到解决方案,我几乎阅读了 SO 中的所有相关帖子。每一个帮助将不胜感激。
在我的getRandomWords()中返回一个承诺,其中一些timeout可能是一个可行的解决方案?
呼唤远方
慕码人2483693
随时随地看视频慕课网APP
相关分类