javascript - 使用 select2 将 php 数组转换为 javascript 数组

标签 javascript php laravel jquery-select2

我在名为 $salaries 的 Laravel 变量中有以下 php 数组,该变量被传递到 Blade View :

array:4 [▼
   2 => "£8, Per hour"
   3 => "£10, Per hour"
   23 => "Up to £10000, Per annum"
   24 => "£10,000 - £15,000, Per annum"
]

在我的 Blade View 中,我有一个下拉菜单,当更改它时,我想加载带有上述选项的 select2 下拉菜单。下面是我的代码:

$(document).on("change", ".js-selector", function() {

     var options = {!! json_encode($salaries) !!};

     $("#salary_list").empty().select2({
        data: options
     });

})

但是,下拉列表中没有加载任何内容。因此,我将范围缩小到 select2 的选项数据格式不正确。

当我将选项变量输出到控制台时,我得到以下对象而不是 JavaScript 数组?

{2: "£8, Per hour", 3: "£10, Per hour", 23: "Up to £10000, Per annum", 24: "£10,000 - £15,000, Per annum"}

如何将选项转换为 select2 数据的正确格式?

最佳答案

您必须将数据转换为正确的格式,here可以看到正确的数据格式:

var data = [
    {
        id: 2,
        text: '£8, Per hour'
    },
    {
        id: 3,
        text: '£10, Per hour'
    }
];

您可以将正确格式的数组传递给 View ,例如:

$salaries = \App\Models\Salary::all(); // eloquent collection

$salaries = $salaries->map(function ($salary) {
    return ['id' => $salary->id, 'text' => $salary->text];
})->toArray();

它会产生如下结果:

array:1 [▼
  0 => array:2 [▼
    "id" => 2
    "text" => "£8, Per hour"
  ]
  0 => array:2 [▼
    "id" => 3
    "text" => "£10, Per hour"
  ]
]

或者您可以在 javascript 中转换数组,Select2 文档解释 here如何转换数据:

Select2 requires that the id property is used to uniquely identify the options that are displayed in the results list. If you use a property other than id (like pk) to uniquely identify an option, you need to map your old property to id before passing it to Select2.

If you cannot do this on your server or you are in a situation where the API cannot be changed, you can do this in JavaScript before passing it to Select2:

var data = $.map(yourArrayData, function (obj) {
  obj.id = obj.id || obj.pk; // replace pk with your identifier

  return obj;
});

在你的情况下,它会是这样的:

$(document).on("change", ".js-selector", function() {

    var options = {!! json_encode($salaries) !!};

    var data = $.map(options, function (value, key) {
        return {id: key, text: value};
    });

    $("#salary_list").empty().select2({
        data: data
    });

})

关于javascript - 使用 select2 将 php 数组转换为 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58221927/

相关文章:

php - Laravel 路由在转移到生产环境后返回 "404 Not Found"错误

javascript - 从 JavaScript 数组返回唯一键

javascript - 输入格式 jQuery

javascript - 可以在任何地方用 Javascript 创建属性吗?

php - 子数组中所有元素的总和 - PHP

php - 如何在 laravel 5 中压缩文件夹?

javascript - 如何增加 IE 10 中的同时 websockets 数量?

php - 显示序列号

PHP/MySQL - 在适当的工作日安排约会

php - Laravel 5.2 用户表中的额外列