我正在编写java / spring webapp,其中每个用户都可以拥有自己的单词列表。每当用户添加/删除一个单词时,就会有一个ajax调用,它发送一个带有这个单词的JSON来添加/删除,当服务器端完成时,则返回JSON对象中的当前单词列表到jQuery。
一切正常。对于小JSON单词列表,添加和删除非常快,但是当单词列表变大时,ajax调用变得更慢。添加/删除呼叫将非常频繁。
JSON单词列表示例[polish 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}]
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;
}
你可以给我一些提示来重构它吗?也许每次用户添加/删除单词时我都不应该返回当前的单词列表?
答案 0 :(得分:1)
要向列表中逐步添加单词对象,请将新单词传递给服务器,并让它只返回一个(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);
}
);
答案 1 :(得分:0)
我会让java / spring处理信息,但只返回一个小字符串,以查看延迟是否在数据传输中。如果java / spring处理数据没有实质性差异,那么它可以在transfer或jquery处理中。您可以通过让jQuery在传输完成时向控制台发送警报来测试它。如果速度很快,则必须使用jQuery处理较长的数据数据。