2013-03-01 79 views
5

以下是從我的coldfusion頁面返回的json字符串的樣子:[{"client":"Asante","id":12},{"client":"City of Lancaster","id":14},{"client":"Massey Energy","id":35},{"client":"Northeast Utilities","id":68},{"client":"Washtenaw","id":50}]。 Firebug聲稱一切正常,但select2插件中沒有任何數據顯示。select2 ajax將不會顯示返回的json數據

有誰知道這個問題可能是什麼?它應該是返回列名或什麼的?

選擇2呼叫:

$(".select").select2({ 
    allowClear: true, 
    blurOnChange: true, 
    openOnEnter: false, 
    ajax: { 
     url: "/surveymanagement/admin/client.cfc", 
     dataType: 'json', 
     data: function (term, page) { 
      return { 
       method: "GetClientsByName", 
       name: term 
      }; 
     }, 
     results: function (data, page) { 
      return { results: data }; 
     } 
    } 
}); 
+1

你的數據格式必須'[{「文本「:」Asante「,」id「:12},...]'否則你需要通過'{results:data,text:'client'}' – 2013-03-01 15:34:01

回答

6

你的數據必須格式化[{"text":"Asante","id":12}, ...]否則你需要通過{results: data, text: 'client'}

6

如果你的JSON字符串需要使用比"text": "something"以外的東西那麼這裏需要補充的東西:使用formatResults讓數據顯示出來。下面是固定的版本:

$(".select").select2({ 
    allowClear: true, 
    blurOnChange: true, 
    openOnEnter: false, 
    ajax: { 
     url: "/surveymanagement/admin/client.cfc", 
     dataType: 'json', 
     data: function (term, page) { 
      return { 
       method: "GetClientsByName", 
       name: term 
      }; 
     }, 
     results: function (data, page) { 
      return { results: data }; 
     } 
    }, 
    formatResult: function (data) { 
     return "<div class='select2-user-result'>" + data.client + "</div>"; 
    }, 
    formatSelection: function (data) { 
     return data.client; 
    } 
}); 

否則阿倫是正確的,你只需要使用的格式[{"id":1,"text":"client"}]

1

是它太老了:)但是今天我需要它,解決它像這樣(使用Symfony2的):

$opts = []; 

foreach($items as $item) 

    $opts['results'][] = ['text' => $item->getXyz(), 'id' => $sk->getId()]; 

return new JsonResponse($opts); 

關鍵 '結果' 是很重要的