【问题标题】:jQuery Select2 JSON datajQuery Select2 JSON 数据
【发布时间】:2017-10-14 06:54:40
【问题描述】:

我的脚本不会在 Select2 中加载任何数据。我用 JSON 数据制作了一个 test.php(一切正常后将在外部提供。(test.php 是我的内部测试))。

test.php 的输出

[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]

jQuery 脚本:

$("#billing_postcode_gemeente").select2({
    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (data) {
            alert(data);
        },
        processResults: function(data) {
            return {
                results: $.map(data.suggestions, function(obj) {
                    return {
                        id: obj.key, text: obj.value
                    }
                })
            };
        }
    }
});

我一直在搜索和检查所有其他解决方案。它对我不起作用。我被卡住了。

更新:到目前为止的 jQuery 脚本

    $("#billing_postcode_gemeente").select2({
    minimumInputLength: 2,
    placeholder: "Voer uw postcode in..",
    ajax: {
        url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (data) {
            return {
            ajax_call: 'addressZipcodeCheck_BE',
            zipcode: '1200'
            };
        },
          processResults: function(data) {
              alert(data);
              correctedData = JSON.parse(data)[0]suggestions;
              alert(correctedData);
                return {
                  results: $.map(correctedData, function(obj) {
                    return {
                      id: obj.key,
                      text: obj.value
                    }
                  })
                };
        }
    }
});

【问题讨论】:

  • 控制台有错误吗?内部测试是什么意思?
  • @SaadSuri 通过内部测试,我的意思是我已经设置了一个自己的 test.php 来回显 json 代码。就这样。现在我看到一个错误: SyntaxError: missing ; before 语句 - LINE: id: obj.key, text: obj.value 我之前还没有这个错误。知道如何解决这个问题吗?
  • 更新:我添加了一个 return { } 。现在没有错误了。但如果我输入“12”,它仍然不会加载我的 JSON 数据。它应该显示我的数据。
  • 你的json文件在不同的服务器上吗?
  • @SaadSuri:目前没有。它是相同的 URL。警报也显示以下内容:[object Object]

标签: php jquery json


【解决方案1】:

Here 是您示例的工作小提琴。 我已经在本地 JSON 对象上完成了 if,但是您可以在响应中复制相同的结果,或者可能相应地更改您的响应。

你的data.suggestions 什么都不是。因为data 是一个 JSON 数组,它的第一个元素是一个 JSON 对象,其键为 suggestions,值为一个建议数组。

在您启用了 JQuery 的浏览器控制台中运行此代码,您将无法理解。

var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;

还可以查看this 的答案,看看正确的响应应该是什么样子。

更新的答案: 向后端发送附加数据:

$('#billing_postcode_gemeente').DataTable(
{
 ......
                    "processing" : true,
                    "serverSide" : true,
                    "ajax" : {
                        url : url,
                        dataType : 'json',
                        cache : false,
                        type : 'GET',
                        data : function(d) {
                            // Retrieve dynamic parameters
                            var dt_params = $('#billing_postcode_gemeente').data(
                                    'dt_params');
                            // Add dynamic parameters to the data object sent to the server
                            if (dt_params) {
                                $.extend(d, dt_params);
                            }
                        }
                    },
});

这里dt_params 是您的附加参数(zipcode 您希望发送到服务器以获得适当的响应)。此 dt_params 被添加到数据表参数中,并且可以在您的后端访问以适应响应。

必须有一个地方可以让您输入zipcode 条目。在该输入框的侦听器上,您可以添加以下代码来销毁并重新创建数据表以反映更改。此代码会将键值对(键为 zip_code)添加到您的请求 JSON 中的 dt_params 键:

function filterDatatableByZipCode() {

        $('#billing_postcode_gemeente').data('dt_params', {
            ajax_call: 'addressZipcodeCheck_BE',
            zip_code : $('#some_imput_box').val()
        });
        $('#billing_postcode_gemeente').DataTable().destroy();
        initDatatable();
    }

【讨论】:

  • 感谢您的完美解释。我现在明白会发生什么。最后一个问题:我正在将数据发送到一个 URL,例如:return { ajax_call: 'addressZipcodeCheck_BE', zipcode: '1500' }。我想确保来自 GET 的这个数据响应将被转换为正确的数据。我该怎么做?
  • 很高兴我能帮上忙。为了社区的利益,请接受答案。如果我理解正确,您希望将 zipcode 添加到您的数据表请求对象以获得适当的响应,如果我是对的,我已经更新了答案以反映这一点。
  • 谢谢。我想要的是在 Select2 框中搜索让我们说邮政编码:1200。它将对 URL 进行 AJAX 调用并得到响应。此响应例如:[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]。如果数据被检索,我想按照您的解释对其进行解析,并将其显示在 Select2 框的下拉列表中。你完全了解我吗?
  • 我用我当前的脚本更新了我的帖子。它对 var CorrectedData 没有任何作用。你明白我现在想要什么了吗?
  • JSON.parse(data)[0]suggestions 中缺少一个 (.)。将其更改为JSON.parse(data)[0].suggestions
【解决方案2】:

试试这个方法

$(".js-data-example-ajax").select2({
    ajax: {
         url: "https://api.github.com/search/repositories",
         dataType: 'json',
         delay: 250,
         data: function (params) {
           return {
              q: params.term, // search term
              page: params.page
           };
        },
        processResults: function (data, page) {
            // 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
           return data.items;
        },
        cache: true
   },
   minimumInputLength: 1,
   templateResult: formatRepo, // omitted for brevity, see the source of this page
   templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

【讨论】:

    猜你喜欢
    • 2015-06-05
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多