使用Select2从服务器检索JSON

时间:2017-04-21 18:53:12

标签: javascript jquery jquery-select2

我正在尝试使用来自服务器的Select2和JSON数据创建一个下拉列表。我试图效仿他们的榜样并且它有效,但我很难完成它。

我使用下面的代码从数据库中获取数据,我可以将其打印到控制台,但我无法将数据显示为下拉列表

$(".js-example-basic-single").select2({
    ajax: {
        url: "DBHandler.php?k=",
        dataType: 'json',
        delay: 250,
        data: function (params) {  
            console.log(params.term);
            return {                     
                search: params.term // search term
            };
        },
        processResults: function (data, params) {
            // parse the results into the format expected by Select2
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data, except to indicate that infinite
            // scrolling can be used
            console.log(data)
            params.page = params.page || 1;
            return {
                results: data.items
                //pagination: {
                    //more: (params.page * 30) < data.total_count
                //}
            };
        },
        cache: true
    },
    escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
    minimumInputLength: 3
});

我的HTML:

<select class="js-example-basic-single form-control" multiple="multiple">
</select>

我的PHP:

$stmt = $this->con->prepare($query);
$stmt->execute();

$results = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode(array_unique($results));   

console.log(data)输出:

Zuber, W. P., Mrs.,Zoellner String Quartet,Zeta Chi,YWCA,Yonge, H. M.,YMCA Friendship Council,YMCA,Yellow Fever,yearbooks,Yarbrough, Reed, Mrs.,Yancey, William L.,Yale University,Yale,Wynne, W. W.,Wynne, Andrew Jackson "Jack",writing,Wright, T. P. (Thomas Parks),Wright, Homer,Wright, G. H.,Wright & Co.,wrestling,Worms Orchestra,World War I,World War 1,World Series,World Fellowship Campaign,Wooten, B. A. (Benjamin Allen),Woodmen's Circle,Woodmen of the World,Woodall, A. M. (Aaron Montgomery),Wood, Leonard, 1860-1927,Wood, Clement, 1888-1950,Wood, C. P.,wood,women,Woman's Missionary Society,Wolcott, Edward Oliver, 1848-1905,Wofford College,Wisconsin,Wirt Society student organizations,Wirt Society,Wirt Literary Society,Winston, Margaret,Winston, E. T.,Windham,

所以我的问题是如何让data.items填充<select></select>标签?

2 个答案:

答案 0 :(得分:1)

我认为你需要以diff方式格式化你的JSON。我将以这种方式粘贴一个需要结构的一个,让子节点items具有至少为{{1的值的数组' }和id(用于下拉列表以填充下拉列表打开时显示的值的值和名称)

name

希望有所帮助,祝你好运,我知道select2可能会在axx中痛苦:)

答案 1 :(得分:0)

就像@Kresimir Pendic所说,问题出在我的JSON字符串上。格式不正确。

  

此代码仅检索一列。然后,它尝试将该数据转换为JSON完全错误

$results = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode(array_unique($results));   
  

要实现正确的结构,我必须创建outputArray。然后我使用for循环遍历result中返回的每个值。我通过创建结构为outputArray的新Array将每个值存储到'id' => $counter, 'text' => $result[0]。创建的每个新Array都被推送到outputArray。最后,我在json_encode($outputArray)outputArray上使用了echo

$outputArray = array();       
for($i = 0; $result = $stmt->fetch(); $i++)
{
    $counter = $i + 1;
    array_push($outputArray, array('id' => $counter, 'text' => $result[0]));  
}        
$json = json_encode($outputArray);
echo $json;