2014-07-10 223 views
1

我想用jquery select2加載數據使用Ajax。一切似乎都是正確的,除非數據在ajax調用成功後沒有顯示。下面是代碼:Select2沒有加載數據到AJAX調用後

$(document).ready(function() 
{ 
    $("#program").select2({ 
     placeholder: "Select a Program", 
     minimumInputLength: 3, 
     ajax: { 
      url: "ajax.php", 
      dataType: 'json', 
      quietMillis: 200, 
      data: function (term, page) { 
       return { 
        term: term, //search term 
        page_limit: 10, // page size 
        page: page // page number 
      }; 
      }, 
      results: function (data) { 
       return {results: data}; 
      } 
     }, 
     dropdownCssClass: "bigdrop", 
     escapeMarkup: function (m) { return m; } 
    }); 
}); 

Ajax代碼:

$search = $mtc->pure['term']; 

$programs = $mtc->db->query("SELECT * FROM program AS program 
    WHERE programcode LIKE '%$search%' OR title_en LIKE '%$search%' OR title_ar LIKE '%$search%' 
"); 

while ($program = $mtc->db->fetch_array($programs)){ 

    $data[] = array("text" => $program['programcode'].' '.$program['title_en'], "id" => $program['programid']); 
} 

$count = number_format($mtc->db->num_rows($programs)); 

unset($programs); 
echo json_encode(array('data' => $data)); 

HTML:

<div class="field-block button-height"> 
    <label for="program" class="label"><b>Program</b></label> 
    <input type="hidden" id="program" class="width-300"> 
</div> 

返回的數據如下:

{"data":[{"text":"MG 101 Negotiation Skills and The Art of Persuasion","id":"1"}, 
{"text":"MG 102 Balanced Score Card","id":"2"}, 
{"text":"MG 103 Effective Manager... Skills and Behaviors","id":"3"}, 
{"text":"MG 104 Building High-Performance Teams","id":"4"}, 
{"text":"MG 105 Measuring Institutional Performance Using RADAR","id":"5"}, 
{"text":"MG 106 How to Be a Distinctive Administrative Leader","id":"6"}, 
{"text":"MG 107 Organizational Excellence Between Requirements and Results","id":"7"}, 
{"text":"MG 108 Effective Negotiation.. Skills and Techniques","id":"8"}, 
{"text":"MG 109 Developing Personal Skills for Manager","id":"9"}]} 

我看着其他問題但我沒有找到任何解決方案。 我不知道我的代碼中的錯誤在哪裏。

+0

確實也更新ajax.php與HTML –

+0

您剛纔提到的返回的數據,所以代碼在AJAX調用之後能夠從腳本的任何位置看到返回的結果? – j809

+0

@ j809它是螢火蟲的延伸。我可以看到所有記錄在那裏。 – ClearBoth

回答

1

愚蠢的問題是在PHP代碼:

echo json_encode(array('data' => $data)); 

它的假設是:

echo json_encode($data);