2016-10-19 30 views
0

我在最後一個版本中使用Select2js。我面臨一個問題。我使用Ajax數據源,並且需要從源代碼獲取數據。Select2js從ajax源獲取數據

這裏是我的代碼:

// call ajax for products 
$('.product-select select').select2({ 
    ajax: { 
     url: baseUrl +'/orders/get_products', 
     processResults: function (data) { 
      return { 
      results: data.items 
      }; 
     }, 
     select: function (data) { 
      // do nothing ... 
      console.log(data); 
     } 
    } 
}); 

$('.product-select select').on('select2:select', function (evt) { 
    // try this but evt doesn't contain data 
    console.log(evt); 
}); 

我的數據源是:

[{id: 3, text: 'test', id_person: 4}, {id: 5, text: 'oooo', id_person: 5}] 

我想每一次我選擇一個行id_person領域。

+0

'。對( '選擇2:選擇'?,功能(EVT,數據){/ * ... * /}' - 什麼是'data' – Tomalak

+0

這是'undefined' :( –

+0

啊,OK。 [documentation](https://select2.github.io/examples.html#events)表明所選數據在'evt.data'內,如果不是這種情況,請設置一個jsFiddle/stack snippet來重現問題 – Tomalak

回答

0

你試過這樣嗎?

$('.product-select select').select2({ 
    ajax: { 
     url: baseUrl +'/orders/get_products', 
     processResults: function (data) { 
      return { 
       results: $.map(data, function (item) { 
        return { 
         text: item.text, 
         id_person: item.id_person, 
         id: item.id 
        } 
       }) 
      }; 
     }, 
     select: function (data) { 
      // do nothing ... 
      console.log(data); 
     } 
    } 
}); 

$('.product-select select').on('select2:select', function (e) { 
    console.log(e.params.data.id_person); 
}); 
+0

它不起作用甚至,如何操作id_person你的代碼後? –

+0

文森特,我編輯我的代碼。你現在可以嘗試 –