所以我對JavaScript相當陌生,我有一個充滿名詞的文本文檔,并認為用這些名詞創建API是多么好的方法。我已讀取文件并將其添加到列表中public List<Noun> getData() throws IOException { Scanner sc = new Scanner(new File("C:\\Users\\Admin\\Desktop\\nounlist.txt")); List<Noun> nouns = new ArrayList(); while (sc.hasNextLine()) { nouns.add(new Noun(sc.nextLine())); } return nouns;}這個列表我用Gson轉換為Json:@GET@Path("/nouns/amount=all")@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)public Response getAllNouns() throws IOException { return Response.ok().entity(gson.toJson(nf.getData())).build();}然后,我開始用js創建我的前端,并試圖獲取數據,但遇到了一個問題,說promise中未被捕獲,類型錯誤,名詞.forEach不是一個函數。import "bootstrap/dist/css/bootstrap.css";const root = document.getElementById("root");var url = "http://localhost:8084/CORSJavaJax-rs/api/noun/nouns/amount=all";var tbody = document.getElementById("tbody");var btn = document.getElementById("btnsend");// fetch(url)// .then(res => res.json)// .then(nouns => {// var n = nouns.map(noun => {// return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";// });// tbody.innerHTML = n.join("");// });btn.addEventListener("click", function() { fetch(url) .then(res => res.json) .then(nouns => { console.log(nouns); var n = nouns.forEach(noun => { return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>"; }); tbody.innerHTML = n.join(""); });});我嘗試了map和forEach,但沒有成功,也許我錯過了一些東西,或者有一些我不明白為什么我不能映射數據的東西。
1 回答
紅糖糍粑
TA貢獻1815條經驗 獲得超6個贊
對于您想要的,正確的用法是調用,而不是 .ForEach 不返回值,它只是循環訪問集合。mapforEach
您收到錯誤的原因很可能是由于 缺少對 的函數調用。它應該是.is not a functionres.jsonres.json()
btn.addEventListener("click", function() {
fetch(url)
.then(res => res.json())
.then(nouns => {
console.log(nouns);
var n = nouns.map(noun => {
return "<tr>" + "<td>" + noun.name + "</td>" + "</tr>";
});
tbody.innerHTML = n.join("");
});
});
添加回答
舉報
0/150
提交
取消
