我正在编写 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/弹簧:
@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;
}
你能给我一些重构它的提示吗?也许每次用户添加/删除单词时我都不应该返回当前单词列表?