Select2 initSelection

前端 未结 2 1409
栀梦
栀梦 2021-01-14 02:16

I have a problem to set the method initSelection with an ajax call, I returns \"undefined\". I checked and the ajax call returns the correct result .. I donot understand the

相关标签:
2条回答
  • 2021-01-14 02:28

    Here the way to solve:

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

    care must be taken that the array is created in the controller and it should be something like this:

    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);
    
    0 讨论(0)
  • 2021-01-14 02:46

    Pay attention, the data you send to the callback function, needs to be an object, with an id and text attributes.

    This is what worked for me:

    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]);
          });
        }
      }
    
    0 讨论(0)
提交回复
热议问题