我有一个用PHP创建的许多选择的表单。表格有3种选择:第二种选择以第一种选择为条件,第三种选择以第二种选择为条件。每个选择都有这样的id:键入[00],键入[01],键入[02]; make [00],make [01],make [02];模型[00],模型[01],模型[02] ......
我使用this script。我试着编辑代码以满足我的需要,但我对java或jquery一无所知。我认为问题是函数finishAjax因为我不知道如何说id对于任何选择都是不同的。
$(document).ready(function() {
$('select[id^="type"]').change(function(){
$('select[id^="make"').fadeOut();
$.post("ajax/ajax_make.php", {
type: $('select[id^="type"]').val()
}, function(response){
setTimeout("finishAjax('make', '"+escape(response)+"')", 400);
});
return false;
});
$('select[id^="make"').change(function(){
$('select[id^="model"').fadeOut();
$.post("ajax/ajax_model.php", {
type: $('select[id^="type"]').val(),
make: $('select[id^="make"').val()
}, function(response){
setTimeout("finishAjax('model', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('select[id^="'+id+'"]').html(unescape(response));
$('select[id^="'+id+'"]').fadeIn();
}
答案 0 :(得分:0)
<select name="type_0" data-id="0" class="type">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<select name="type_1" data-id="1" class="type">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<select name="make_0" data-id="0" class="make">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<select name="make_1" data-id="1" class="make">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<script type="text/javascript">
$(document).ready(function() {
/** Execute an ajax request **/
function dispatchRequest(url, data, timeout)
{
setTimeout(function() {
$.ajax({
type : "POST",
url : url,
data : data,
success : finishAjax,
type : "JSON"
});
}, timeout);
};
/** Finish AJAX request **/
function finishAjax(response)
{
/** IMPORTANT
response is now a JSON object, this is just a simple string
that represents a complex object. I this case, it is up to the
target URL (ajax/ajax_make.php) to create this string by using
the provided data (id,type)
At a minimum we need three values:
response.HTML = HTML of the select options
response.id = The identity of the select item
response.type = The type of select option
**/
$("select[name=" + response.type + "_" + response.id)
.html(unescape(response.html))
.fadeIn();
}
/** Find ALL the selects of each type, hence class selector **/
$selectType = $(".type");
$selectMake = $(".make");
/**
Change event for "type" select option
**/
$selectType.on("change", function(){
var id = $(this).data("id");
/** Hide all "make" select options **/
$selectMake.each(function(){
$(this).fadeOut();
});
dispatchRequest("ajax/ajax_make.php", {
id : $(this).data("id"),
type : $(this).attr("class")
}, 1000);
return true;
});
});
</script>
重要的变化是响应是一个JSON对象,包含多个键值对 - 其中一个是您需要的“id”。
注意:这是未经测试的午餐时间代码。当我有机会时,我会测试并给出更好的解释。与此同时,希望代码可以为您提供一些见解..