简体   繁体   中英

Jquery Select2 4 - Ajax “no results found” when using custom data

I can't get the Ajax example to work outside of the github example on the documentation page .

Here's what I'm trying:

https://jsfiddle.net/vhrpzcuv/8/

<select name="test" class="select2picker" style="width: 100%">
 <option value="test">test</option>
</select>

    $('.select2picker').select2({
    ajax: {
        url: "", //For testing don't do this.  
        dataType: 'json',
        data: function(params) {
            return {
                filter: params.term // search term
            };
        },
        processResults: function(data) {
            data = [{
                id: 0,
                text: 'enhancement'
            }];
            console.log(data);
            return data;
        }
    }
});

The returned data needs to be wrapped with an object {results:x} .

https://jsfiddle.net/vhrpzcuv/9/

$('.select2picker').select2({
    ajax: {
        url: "", //For testing don't do this.  
        dataType: 'json',
        data: function(params) {
            return {
                filter: params.term // search term
            };
        },
        processResults: function(data) {
            data = [{
                id: 0,
                text: 'enhancement'
            }];
            console.log(data);
            return {results: data};
        }
    }
});

You need also set the header in your PHP (or else) file.

For PHP reponse file example:

header('Content-Type: application/json');
echo json_encode($data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM