【问题标题】:Select2: Results not showing using AJAXSelect2:使用 AJAX 未显示结果
【发布时间】:2013-06-12 19:05:54
【问题描述】:

我无法使用 AJAX 将结果显示在 Select2 中。 这是我的代码:

$(document).ready(function() {
    $("#producto").select2({
        placeholder: 'Select a product',
        formatResult: productFormatResult,
        formatSelection: productFormatSelection,
        dropdownClass: 'bigdrop',
        escapeMarkup: function(m) { return m; },
        minimumInputLength:3,
        ajax: {
            url: 'http://foo.foo/listar.json',
            dataType: 'jsonp',
            data: function(term, page) {
                return {
                    q: term
                };  
            },  
            results: function(data, page) {
                return {results:data};
            }   
        }   
    });


function productFormatResult(product) {
    var html = "<table class='product-resultado'><tr>";
    if(product.img != undefined) {
        html += "<td class='product-image'><img src='"+product.img+"'/></td>";
    }
    html += "<td class='product-info'>";
    html += product.text + "<br />";
    html += product.precio_costo + " CRC <br />";
    html += "Existencias: " + product.existencias;
    html += "</td></tr></table>";
    return html;
}

function productFormatSelection(product) {
    return product.text;
}

使用 Javascript 控制台,我看到请求返回了预期的 JSON:

[

{ "text":"Foo 产品", "img":"#", "precio_costo": 45, "existencias":0, "id":2 }

]

我相信结果:function(data, page) { ... } 没有被调用,因为我在那里发出警报,但什么也没发生。

它只是挂在那里等待结果:

【问题讨论】:

    标签: javascript ajax jsonp jquery-select2


    【解决方案1】:

    我猜你返回的是 json 而不是 jsonp,

    所以尝试将行 dataType: 'jsonp' 更改为 dataType: 'json', 甚至删除整行。

    我以前也有过同样的经历。 json结果被这个标准筛选掉, 即使实际返回了预期的 JSON,也很可能是因为 json 和 jsonp 被视为两种不同的格式

    PS:这更像是评论,但由于我无法评论您的问题,请多多包涵

    【讨论】:

      【解决方案2】:

      我认为你不能从 ajax 调用中返回值,因为 ajax 调用是asynchronous。而是自己处理那里的结果。或使用下面链接中给出的callback functions

      jQuery: Return data after ajax call success

      【讨论】:

      • 这不是简单的 Ajax 调用,它是一个插件。或者你知道dataresults 回调是如何工作的吗?
      • 是的,从文档中它说“这个对象充当了手动编写执行 ajax 请求的函数的快捷方式。内置函数支持更高级的功能,例如节流和退出-有序响应。” -- ivaynberg.github.io/select2
      • @Felix Kling ya 我知道回调是如何工作的,比如传递一个函数指针,这样函数就会被指针调用。另外,我知道 ajax 调用是异步的,它不能返回一个值。而且我认为 OP 在那里滞后,因为 ajax 概念在任何地方都是相同的。因此给出了一个建议。因此,在回答中我输入了“我认为”。承认 - 我不知道他工作的确切场景。我在哪里回答错了吗??
      猜你喜欢
      • 2016-09-11
      • 1970-01-01
      • 2016-04-10
      • 2018-11-22
      • 1970-01-01
      • 2015-10-15
      • 2017-08-16
      • 2020-01-25
      • 2016-10-30
      相关资源
      最近更新 更多