JQuery问题/错误

时间:2011-01-12 12:59:49

标签: jquery ajax

我在使用JavaScript时遇到问题。

请找到下面的代码,我正在尝试进行AJAX调用。当我手动输入名称(注释代码)时,它工作正常,但是当我使用AJAX调用时,它不会将正确的数据添加到下拉列表中。

$(function() {
    /* var names = [
        { value: 1, label: "Marcus Ekwall" },
    { value: 1.1, label: "Marcus 1" },
        { value: 2, label: "John Resig" },
        { value: 3, label: "Eric Hynds" },
        { value: 4, label: "Paul Irish" },
        { value: 5, label: "Alex Sexton" }
    ];*/

    var names = "";
    var container = $("div.ui-tagging"),
    highlight = container.children("div.highlight"),
        textArea = container.find("textarea"),
     meta = container.children("input.meta"),
        activeSearch = false,
        searchTerm = "",
        beginFrom = 0;

    textArea.keypress(function(e){
        // activate on @
        if (e.which == 64 && !activeSearch) {
            activeSearch = true;
            beginFrom = e.target.selectionStart+1;
        }

        // deactivate on space
        if (e.which == 32 && activeSearch) {
            activeSearch = false;
        }
    }).bind("keyup change", function(e){
        var cur = highlight.find("span"),
            val = textArea.val();
        cur.each(function(i){
            var s = $(this);
            val = val.replace(s.text(), $("<div>").append(s).html());
        });
        highlight.html(val);
    }).autocomplete({
        minLength: 0,
        delay: 0,
        open: function(event, ui) {

            //console.log(ui);
        },

        source: function(request, response) {
            if (activeSearch) {
                searchTerm = request.term.substring(beginFrom);
                if (request.term.substring(beginFrom-1, beginFrom) != "@") {
                    activeSearch = false;
                    beginFrom = 0;
                    searchTerm = "";
                }

                if (searchTerm != "") {
                    var re = new RegExp("^"+escape(searchTerm)+".+", "i");
                    var matches = [];
                    $.ajax({
                        url: '/search.asp?SearchTerm=' + searchTerm,
                        success: function(data) {
                            var names = data;
                            alert(names);
                        }

                    });

                    $.each(names, function(){
                        if (this.label.match(re)) {
                            matches.push(this);
                        }
                    });
                    response(matches);
                }
            }
        },

        focus: function() {
            // prevent value inserted on focus
            return false;
        },

        select: function(event, ui) {
            activeSearch = false;
            //console.log("@"+searchTerm, ui.item.label);

            this.value = this.value.replace("@"+searchTerm, ui.item.label)+' ';
            highlight.html(highlight.html().replace("@"+searchTerm, '<span class="ui-corner-all">'+ui.item.label+'</span>')+' ');

            meta.val((meta.val()+" @["+ui.item.value+":]").trim());
            return false;
        }
    });
});

2 个答案:

答案 0 :(得分:1)

您需要考虑Ajax的异步特性。您需要通过在调用中设置async: false来使您的ajax调用同步,或者您需要使用名称将代码移动到success回调的正文中。所以:

$.each(names, function(){
  if (this.label.match(re)) {
    matches.push(this);
  }
});
response(matches);

应该是成功的。否则,当您点击它时,名称可能会为空。

答案 1 :(得分:0)

正如justkt所说,如果在从AJAX请求获得响应后调用所有代码,您仍然可以使用异步。这是一个清理过的代码:

$(function () {
    var names = "",
        container = $("div.ui-tagging"),
        highlight = container.children("div.highlight"),
        textArea = container.find("textarea"),
        meta = container.children("input.meta"),
        activeSearch = false,
        searchTerm = "",
        beginFrom = 0,
        bindTextAreaEvents = function (textArea, data) {
            names = data;

            textArea.keypress(function (e) {
                // activate on @
                if (e.which === 64 && !activeSearch) {
                    activeSearch = true;
                    beginFrom = e.target.selectionStart + 1;
                }
                // deactivate on space
                if (e.which === 32 && activeSearch) {
                    activeSearch = false;
                }
            }).bind("keyup change", function (e) {
                var cur = highlight.find("span"),
                    val = textArea.val();
                cur.each(function (i) {
                    var s = $(this);
                    val = val.replace(s.text(), $("<div>").append(s).html());
                });
                highlight.html(val);
            }).autocomplete({
                minLength: 0,
                delay: 0,
                open: function (event, ui) {
                    //console.log(ui);
                },
                source: function (request, response) {
                    if (activeSearch) {
                        searchTerm = request.term.substring(beginFrom);
                        if (request.term.substring(beginFrom - 1, beginFrom) !== "@") {
                            activeSearch = false;
                            beginFrom = 0;
                            searchTerm = "";
                        }

                        if (searchTerm !== "") {
                            var re = new RegExp("^" + escape(searchTerm) + ".+", "i"),
                                matches = [];

                            $.each(names, function () {
                                if (this.label.match(re)) {
                                    matches.push(this);
                                }
                            });
                            response(matches);
                        }
                    }
                },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    activeSearch = false;
                    //console.log("@"+searchTerm, ui.item.label);
                    this.value = this.value.replace("@" + searchTerm, ui.item.label) + ' ';
                    highlight.html(highlight.html().replace("@" + searchTerm, '<span class="ui-corner-all">' + ui.item.label + '</span>') + ' ');

                    meta.val((meta.val() + " @[" + ui.item.value + ":]").trim());
                    return false;
                }
            });
        };

    $.ajax({
        url: '/search.asp?SearchTerm=' + searchTerm,
        success: function (data) {
            bindTextAreaEvents(textArea, data);
        }
    });
});