的代码包含一些小的错误,除了那些在其他意见处理。例如,您拨打change()
,电话号码为$('type')
,而不是$('#type')
。另外,并非所有的浏览器都没有提供JSON的内容类型。
一般来说这个问题是由两个部分组成:
从JSON jQuery中
function fillCombo($combo) {
$.post('/url/to/php/endpoint',
{ search: '%' },
function(options) {
for (i in options) {
$combo[0].options[i] = {
value: options[i].value,
text : options[i].text
};
}
$combo.change();
}
);
}
fillCombo($('#comboBox');
获取的数据,并输出JSON
// Here I strongly suggest to use PDO.
$dbh = new PDO('mysql:host=localhost;port=3306;dbname=database', 'user', 'password',
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
$query = "SELECT kat_id, kategorite FROM kategorite WHERE kategorite LIKE :search";
$stmt = $dbh->prepare($query);
// Always check parameter existence and either issue an error or supply a default
$search = array_key_exists('search', $_POST) ? $_POST['search'] : '%';
$stmt->bindParam(':search', $search, PDO::PARAM_STRING);
$stmt->execute();
$reply = array();
while ($tuple = $stmt->fetch(PDO::FETCH_NUM)) {
$reply[] = array(
'value' => $tuple['kat_id'],
'text' => $tuple['kategorite'],
);
};
// See: http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type
Header('Content-Type: application/json');
// Adding Content-Length can improve performances in some contexts, but it is
// needless with any kind of output compression scheme, and if things go as they
// should, here we have either zlib or gz_handler running.
// die() ensures no other content is sent after JSON, or jQuery might choke.
die(json_encode($reply));
填充组合框在这种情况下,由于返回的数据与comboBox使用的格式相同,也可以缩短和加速以下内容:
function(options) {
$combo[0].options = options;
$combo.change();
}
一般而言,您希望服务器尽可能少地做些工作(服务器负载成本金钱和影响性能),而且客户端尽可能少做工作(客户端负载影响网站的感知和响应度)。什么样的数据交换格式是值得思考的东西。
对于很长的没有分页的列表,例如,您可能希望通过仅对该选项的文本进行编码来剪切正在发送的数据。然后,您将发送的
[ 'make1','make2','make3'... ]
代替
[ { "option": "1", "value": "make1" }, { "option": "2", "value": "make2" }, ... ]
,并使用较慢的客户周期来填充组合框。
定义“没有工作”。 – undefined 2015-01-04 12:26:34
是的。我的下拉列表仍然是empy – MrVampo 2015-01-04 12:27:45
您只能从表中选择'kategorite'('kategorite FROM kategorite'?)字段,所以'$ row'没有'Lloji'键。你还没有关闭ready函数,缺少'})'。请学习调试。口译员会告诉你你的代码有什么问题。 – undefined 2015-01-04 12:33:31