1

我正在编写 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;
}

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

4

2 回答 2

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);
  }
 );
于 2012-05-26T00:06:49.967 回答
0

我会让 java/spring 处理信息,但只返回一个小字符串来查看数据传输是否存在延迟。如果java/spring处理数据没有本质区别,那么要么是在transfer,要么是jquery处理。您可以通过让 jQuery 在传输完成时向控制台发送警报来测试这一点。如果速度很快,那么它必须是 jQuery 处理较长的数据数据。

于 2012-05-25T19:22:14.157 回答