【发布时间】:2011-03-04 08:12:05
【问题描述】:
EDIT 2 似乎是 CSS 类的问题。
编辑 奇怪的是,它在网站的公共方面工作,而不是私人。它必须是 css 或与另一个插件冲突。
首先让我说我很少有 jQuery 经验,这是我第一次涉足 ajax。
我要做的是根据上一个下拉列表的选择动态填充下拉数据。
我有一个看起来像这样的 html
<label for="employee_type">Employee Type</label>
<select name="employee_type" id="employee_type">
<option value="1" selected="selected">Team Member</option>
<option value="2">Supervisor</option>
<option value="3">Manager</option>
</select>
<label for="manager">Reports To</label>
<select name="manager" id="manager_name">
<option value="0" selected="selected">Please Select Employee Role</option>
</select>
The Idea being that when an employee role or type is selected that the field below populates with all the managers who are higher up on the food chain.
我有一个用 php 编写的 MYSQL 选择字符串,它使用 json_encode 输出一些 json,其输出是
[{"id":"2","first_name":"John","last_name":"Doe"}]
这基本上只是一个包含所有用户及其姓名和 ID 的数组,这些用户将显示在数组中。
这里是棘手的部分,ajax。我找到了this tutorial,我已经修改了
// attach a change handler to the form
$("select#employee_type").change(function(){
//get the mininimum employee level
var input = $("select#employee_type").val();
//get the callback url
var ajax_url = "/admin/employee/get_json/"+input;
$.ajax({
url:ajax_url,
data:{ url:escape(ajax_url) },
dataType:"json",
success:function(data){
var select = $('#manager_name');
var options = select.attr('options');
$('option', select).remove();
$.each(data, function(index, array) {
options[options.length] = new Option(array['first_name']+ " "+array['last_name'],array['id']);
})
},
error:function(xhr,err,e){ alert( "Error: " + err ); }
}); // $.ajax()
return false;
}); // .submit()*/
这大约可以完成 78% 的工作。它添加了正确的选项和价值。它失败的地方是,如果我有$('option', select).remove();(这是确保每次字段更改时都不会添加值的必要条件)当我尝试单击该字段时,该字段将被删除。我也认为删除所选选项(请选择...)会很好。
在这方面的任何帮助都会很棒!
【问题讨论】:
标签: javascript ajax jquery