使用Ajax选择二加载数据文件 [英] Select2 load data with Ajax from file

查看:280
本文介绍了使用Ajax选择二加载数据文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为脚本 listofValues​​.php ,其查询数据库,并返回JSON格式的值。

I have a script called listofValues.php, which queries a database and returns JSON format values.

我需要的是将这些值传递给选择2 数据成员。我需要它来加载一次。

What I need is to pass these values to the select2 data member. I need it to load once.

我所描述的并不需要从选择2 将值输入(长期),以我的 listofValues​​.php 这个例子

I don't need to pass values from select2 input (term) to my listofValues.php as described in this example

$('#select2div').select2({
        //data:[],
    ajax: {
        dataType: "json",
        url: "listofvalues.php",    
        success: function (data) {          
        }
    }

您可以帮我这个?

推荐答案

这将是知道你正在从 listofvalues​​.php 返回对象的格式是有用的,但我们只是假设,为简单起见,它看起来像这样的:

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"} ]

这是使用,因为默认情况下最简单的格式,选择2 可以处理的属性名对象 ID 文本,使它们成为一个下拉列表。所以,你的选择2 初始化可能是这样的:

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

稍微复杂一些示例

现在让我们假设从数据 listofvalues​​.php 不遵循方便的命名约定:

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

和我们的选择2 初始化:

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

让我知道你上车。

Let me know how you get on.

这篇关于使用Ajax选择二加载数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆