0

I'm using Textextjs autocomplete with tags
In the above example list is a simple json array.
And I want to get its value from ajax function.

In this case ajax call is executed late. So the expected result is disturbed. Have a look on below code

$('#textarea')
.textext({
    plugins : 'tags autocomplete'
})
.bind('getSuggestions', function(e, data)
{
    console.log(1);
    search_text = (data ? data.query : '') || '';
    var urll = 'url_to_get_result';

    // call ajax function
    var suggestionss = getSuggestions(search_text, urll);

    console.log(4);
    $("#output1").val();
    var list = suggestionss,

    textext = $(e.target).textext()[0],
    query = (data ? data.query : '') || '';

    $(this).trigger(
        'setSuggestions',
        { result : textext.itemManager().filter(list, query) }
    );
});

function getSuggestions(search_text, urll)
{
    console.log(2);
    $.ajax({
        'url': urll,
        'data': {'wt':'json'},
        type: 'GET',
        'success': function(data) {
            jsonObj = [];
            var count = data.count.length;
            for(i=0; i<count; i++)
            {
                var name = data.name.docs[i].term_suggest_ngram;
                autosuggestitem = {}
                autosuggestitem = '"'+name+'"';
                jsonObj.push(autosuggestitem);
            }
            var result = JSON.stringify(jsonObj);
            availableSearch = JSON.parse(result);
            console.log(3);
            $("#output1").val(availableSearch);
        },
        'dataType' : 'jsonp',
        'jsonp': 'json.wrf'
    });
    var return_val = $("#output1").val();
    return return_val;
}

See the console statements, these are executed in sequence
1 - 2 - 4 - 3
Expected behavior should be
1 - 2 - 3 - 4

Can someone help me?

4

1 回答 1

0

异步就是答案。之后的代码var suggestionss = getSuggestions(search_text, urll);不会等待 getSuggestions 方法完成。所以这些行应该进入 ajax 的 .done() 或 .success() 方法

$('#textarea')
.textext({
    plugins : 'tags autocomplete'
})
.bind('getSuggestions', function(e, data)
{
    console.log(1);
    ......
    var self = $(this); // <--- store a reference of this
    getSuggestions(search_text, urll).done(function(){ // <--- .done() method of the returned ajax is invoked
       console.log(3);
       console.log(4);
       .....
       textext = $(e.target).textext()[0],
       query = (data ? data.query : '') || '';

       self.trigger( // <---- stored reference
         'setSuggestions',
          { result : textext.itemManager().filter(list, query) }
       );
    });
});

function getSuggestions(search_text, urll) {
  console.log(2);
  return ajax({ // <---- notice that ajax is returned here

  });
}
于 2015-07-16T14:42:48.043 回答