gpt4 book ai didi

java - 重构大型 JSON 多次调用

转载 作者:太空宇宙 更新时间:2023-11-04 08:13:52 25 4
gpt4 key购买 nike

我正在编写 java/spring webapp,其中每个用户都可以有自己的单词列表。每当用户添加/删除一个单词时,都会有一个 ajax 调用,它会发送一个带有该单词的 JSON 来添加/删除,当服务器端完成时,就会将 JSON 对象中的当前单词列表返回给 jQuery。

一切正常。对于小型 JSON 单词列表,添加和删除非常快,但是当单词列表变大时,ajax 调用会变得更慢。并且添加/删除调用将会非常频繁。

JSON 单词列表示例 [抛光单词]:

 [{"word":"abrys","wordId":646},{"word":"acpan","wordId":647},
{"word":"akrania","wordId":457},{"word":"akwawita","wordId":648},
{"word":"amalgamat","wordId":399},{"word":"amurski","wordId":465},
{"word":"amurskie","wordId":1030},{"word":"ananke","wordId":649},
{"word":"androlog","wordId":650}]

jQuery [或多或少]:

$("#add_word_submit").live("click", function(e) {
e.preventDefault();
var word = $('#add_word').serializeObject();
$.postJSON("word.html", word, function(words) {
showDividedAccountWords(words);
});
});

$(".delete_button").live("click", function(e) {
e.preventDefault();
if(confirm(Main.confirmWordDelete)) {
var wordId = $(this).attr("id").substring("delete_".length);
wordName["word"] = $(this).children("img").attr("alt");
$.ajax({
type: "DELETE",
url: "word/" + wordId + ".html",
success: function(words) {
showDividedAccountWords(words);
}
});
}
});

Java/Spring:

@RequestMapping(value="/word", method = RequestMethod.POST)
public @ResponseBody List<Word> addNewWord(@RequestBody Word word, Principal principal) {
wordService.addNewWord(word, principal.getName());
return getCurrentWords(principal.getName());
}

@RequestMapping(value="/word/{wordId}", method = RequestMethod.DELETE)
public @ResponseBody List<Word> deleteWord(@PathVariable Long wordId, Principal principal) {
wordService.deleteWord(wordId, principal.getName());
return getCurrentWords(principal.getName());
}

public List<Word> getCurrentWords(String username) {
List<Word> accountWords = new ArrayList<Word>();
accountWords.addAll(wordService.listUserWords(username));
return accountWords;
}

您能给我一些重构的提示吗?也许我不应该在每次用户添加/删除单词时返回当前单词列表?

最佳答案

要将单词对象增量添加到列表中,请将新单词传递到服务器并让它仅返回一个 (word:wordid) 对象。然后,您可以将其添加到现有列表中并按如下方式排序:

var words=[{"word":"abrys","wordId":646},{"word":"acpan","wordId":647},
{"word":"akrania","wordId":457},{"word":"akwawita","wordId":648},
{"word":"amalgamat","wordId":399},{"word":"amurski","wordId":465},
{"word":"amurskie","wordId":1030},{"word":"ananke","wordId":649},
{ "word": "androlog", "wordId": 650}];


var result = { "word": "aklina", "wordid": "702" }; // returned by server from AJAX call
words.push(result);

words.sort(
function(a, b) {
return a.word.localeCompare(b.word);
}
);

关于java - 重构大型 JSON 多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10760005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com