2016-04-03 98 views
1

我在搜索框中使用了select2倍數。我使用JSON傳遞這些數據並使用ajax(JSON stringify)保存它。Select2要傳遞給JSON的多種格式

我只需要2個變量傳遞,這是ID(主鍵,自定義)和選擇本身。

當我只選擇1個值時,我設法將它保存到數據庫中。

如果選擇多個值,在我的console.log,我看到這樣的事情

{21,23,25,26} 

這是選擇本身。

我如何得到它顯示這個樣子,

Object0->{id:1, selection:21} 
Object1->{id:2, selection:23} 
Object2->{id:3, selection:25} 
Object3->{id:4, selection:26} 

下面是我使用的代碼,

var nature = { 
    ubtBusinessInfo: businessId, // the primary key 
    ubtBusinessListing: nature.val() // here is selection 
}; 

這裏是選擇2的初始化,

nature 
    .select2({ 
     allowClear: true, 
     placeholder: "Filter as you type", 
     minimumInputLength: 3, 
     multiple: true, 
     ajax: { 
      url: 'home/umkei/info/nature', 
      dataType: 'json', 
      quietMillis: 250, 
      data: function (term, page) { 
       return { q: term }; 
      }, 
      results: function (data, page) { 
       return { results: data }; 
      }, 
      cache: true 
     } 
    }) 

性質定義如下(我試過如下)

var nature = $('[name=nature_business]') OR var nature = $(#nature_business); 

我知道它必須與nature.val()的用法有關。一定是像數組一樣,但我不知道如何區分/分割這些數據是鍵 - >值對。

謝謝。

回答

1

上週我得到了這件事,並認爲我會分享我的解決方案。

var nature=[]; 
var splitnature = nature_business.val().trim().split(','); 
var n; 

for(n=0; n<=splitnature.length-1;n++){ 
    nature.push({ 
    ubtBusinessListing: splitnature[n], 
    ubtBusinessInfo: businessId 
    }); 
} 
相關問題