【问题标题】:Select2 data returning string instead of arraySelect2 数据返回字符串而不是数组
【发布时间】:2016-08-24 18:07:05
【问题描述】:

我的 html 中有几个 <select class="searchselect"> 标记,全部用数值填充。我正在使用以下代码来初始化 Select2:

$(".searchselect").select2({
        ajax: {
            dataType: "json",
            type: "POST",
            data: function (params) {
                return {
                    term: params.term,
                    '_token': token,
                    'data': function () {
                        var result = [];
                        var i = 0;
                        $('.searchselect').each(function () {
                            result[i] = $(this).val();
                            i++;
                        });

                        return result;
                    }
                };
            },
            url: function () {
                var type = $(this).attr('id');
                return '/test/get' + type;
            },
            cache: false,
            processResults: function (data) {
                console.log(data);
                return {
                    results: data
                };
            }
        }
     }); 

在我的 php 中,我有以下代码:

public function getTest()
{
    return json_encode($_POST['data']);
}

返回的 php 被登录到控制台。

结果是一个用逗号分隔元素的字符串。然而,这不是它应该的样子。它是这样的:1,1,,,,,,(前两个选择字段已填满,其余字段仍为空)。这是正确的,但是,当我尝试访问第二个元素(数组中的第二个 1)时,我需要访问第三个元素,因为第二个元素是逗号。

public function getTest()
{
    return json_encode($_POST['data'][2]); // <--- this returns a comma instead of a 1
}

哪里出错了?为什么使用纯字符串而不是数组?

【问题讨论】:

  • json_decode 而不是 json_encode?​​span>
  • 尝试 return $_POST['data']; 而不使用 json_encode,因为它已经在 J​​SON 中了

标签: javascript php arrays json ajax


【解决方案1】:

将你的函数 getTest() 更改为

public function getTest()
{
    return json_decode($_POST['data']);
}

您正在将 json 对象编码为字符串,而不是将其解码为数组。

【讨论】:

    猜你喜欢
    • 2011-09-20
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    相关资源
    最近更新 更多