4

我在使用 ajax 调用设置方法 initSelection 时遇到问题,我返回“未定义”。我检查并ajax调用返回正确的结果..我不明白如何设置回调方法以确保您选择'预设值。

 function mediaFormatResult(media) {
        var markup = "<div class='media-title'>" + media.name + ", " + media.prov + " (" + media.region + ")</div>";

        return markup;
    }

    function mediaFormatSelection(media) {
        return media.name +", " + media.prov + " (" + media.region + ")";
    }
    $field = $('#comune');
    $($field).select2({
        placeholder: "Seleziona il tuo comune",
        minimumInputLength: 3,
        initSelection: function(element, callback) {

        return $.ajax({
            type: "POST",
            url: "myurl",
            dataType: 'json',
            data: { id: (element.val())},
            success: function(data){
                //results: data.results;
            }
        }).done(function(data) { 
            //console.log(data);
            callback(data);
        });

        },
        ajax: { 
            quietMillis: 100,
            url: "myurl",
            dataType: 'json',
            type: 'POST',
            data: function (term, page) {
                return {
                    q: term,
                    page_limit: 10
                };
            },
            results: function (data, page) {
                return {results: data.results};
            }
        },
        formatResult: mediaFormatResult, 
        formatSelection: mediaFormatSelection, 
        formatNoMatches: function () { return "Nessun risultato trovato!";},
        formatSearching: function () { return "Ricerco.."; },
        formatInputTooShort: function(input, min) {return "Inserire "+ (min - input.length) + " caratteri.";},
        dropdownCssClass: "bigdrop",
    });

有什么不对吗?

4

2 回答 2

12

注意,你发送给回调函数的数据,需要是一个对象,有idtext属性。

这对我有用:

initSelection: function(element, callback) {
    var id;
    id = $(element).val();
    if (id !== "") {
      return $.ajax({
        url: url,
        type: "POST",
        dataType: "json",
        data: {
          id: id
        }
      }).done(function(data) {
        var results;
        results = [];
        results.push({
          id: data.id,
          text: data.name
        });
        callback(results[0]);
      });
    }
  }
于 2014-02-10T09:16:10.060 回答
3

这里的解决方法:

initSelection: function(element, callback) {

        return $.ajax({
            type: "POST",
            url: path,
            dataType: 'json',
            data: { id: (element.val())},
            success: function(data){

            }
        })

必须注意数组是在控制器中创建的,它应该是这样的:

foreach ($entities as $member) {
        $json['id'] = $member->getId();
        $json['name'] = $member->getComune();
        $json['region'] = $member->getRegione()->getRegione();
        $json['prov'] = $member->getProvincia()->getSigla();
}

        $result = $json;
        return json_encode($result);
于 2013-03-16T20:39:26.823 回答