开发者

JQuery Problem/Error

开发者 https://www.devze.com 2023-02-04 08:14 出处:网络
I am having a problem getting some JavaScript to work. Please find the code below, I am trying to do an AJAX call. When I put in the names manually (commented code) it works fine, but when I use the

I am having a problem getting some JavaScript to work.

Please find the code below, I am trying to do an AJAX call. When I put in the names manually (commented code) it works fine, but when I use the AJAX call it doesn't add the correct data to the dropdown.

$(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);
                }
开发者_JS百科            }
        },

        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;
        }
    });
});


You need to take into account the asynchronous nature of Ajax. Either you need to make your ajax call synchronous by setting async: false in the call, or you need to move code using names into the body of your success callback. So the:

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

Should be in success. Otherwise names will likely be empty when you hit it, as you are seeing.


As justkt said you can still use async if you invoke all code after you get the response from the AJAX request. Here's a cleaned up code:

$(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);
        }
    });
});
0

精彩评论

暂无评论...
验证码 换一张
取 消