jQuery的自动完成与Mockjax的

时间:2018-07-25 06:38:53

标签: jquery ajax jquery-ui-autocomplete mockjax

我是mackjax的新手,请告诉我如何使用下面给出的代码处理来自url而非本地数据(即国家/地区数组)的数据。该代码对于文件countries{}中的本地数组工作正常,但是如何使其适用于来自网址的数据

var countries= {
                "AZ": "Azerbaijan",
                "BA": "Bosnia and Herzegovina",

            }

var countriesArray = $.map(countries, function (value, key) { return { value: value, data: key }; });

// Setup jQuery ajax mock:
$.mockjax({
    url: '*',
    responseTime: 2000,
    response: function (settings) {
        var query = settings.data.query,
            queryLowerCase = query.toLowerCase(),
            re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi'),
            suggestions = $.grep(countriesArray, function (country) {
                 // return country.value.toLowerCase().indexOf(queryLowerCase) === 0;
                return re.test(country.value);
            }),
            response = {
                query: query,
                suggestions: suggestions
            };

        this.responseText = JSON.stringify(response);
    }
});

// Initialize ajax autocomplete:
$('#autocomplete-ajax').autocomplete({
    // serviceUrl: '/autosuggest/service/url',
    lookup: countriesArray,
    lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
        var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
        return re.test(suggestion.value);
    },
    onSelect: function(suggestion) {
        $('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
    },
    onHint: function (hint) {
        $('#autocomplete-ajax-x').val(hint);
    },
    onInvalidateSelection: function() {
        $('#selction-ajax').html('You selected: none');
    }
});

0 个答案:

没有答案