Select2 load data with Ajax from file

不羁岁月 提交于 2019-12-03 13:22:19

Simple Example

It would be useful to know the format of the object you're getting back from listofvalues.php, but let's just assume, for the sake of simplicity it looks like this:

[ {"id": 1, "text": "option1"},
  {"id": 2, "text": "option2"},
  {"id": 3, "text": "option3"} ]

This is the easiest format to use, as by default, select2 can handle objects with property names id and text and render them into a dropdown list. So your select2 initialisation might look like this:

$('#select2div').select2({
    ajax: {
        dataType: "json",
        url: "listofvalues.php",
        results: function (data) {
            return {results: data};
        }
    }
});

Slightly Trickier Example

Now let's assume the data from listofvalues.php doesn't follow the convenient naming conventions:

[ {"id": 1, "firstName": "John", "lastName": "Lennon"},
  {"id": 2, "firstName": "Paul", "lastName": "McCartney"},
  {"id": 3, "firstName": "George", "lastName": "Harrison"},
  {"id": 4, "firstName": "Ringo", "lastName": "Starr"} ]

We'll have to set up a function to handle the output:

function formatValues(data) {
    return data.firstName + ' ' + data.lastName;
}

And our select2 initialisation:

$('#select2div').select2({
    ajax: {
        dataType: "json",
        url: "listofvalues.php",
        results: function (data) {
            return {results: data};
        }
    },
    formatResult: formatValues
});

Let me know how you get on.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!