我正在尝试使用jquery select2来使用ajax加载数据。一切似乎都是正确的,除了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 :(得分:1)
愚蠢的问题出现在PHP代码中:
echo json_encode(array('data' => $data));
它应该是:
echo json_encode($data);