我需要根据用户在一个或多个选择字段中选择的内容,使用jquery加载PHP文件的内容。
我可以用......
$("#first-choice").change(function() {
$("#second-choice").load("getter.php?choice=" + $("#first-choice").val() );
});
...创建变量'choice'以及用户设置'first-choice'字段时。
但是,如果我想基于两个下拉选择器使用2个变量,设置变量'choice'(基于#first-choice的选择)和choice2(基于#second-choice的选择)怎么办? )。
所以我想加载一个像getter.php这样的PHP文件?choice = first-choice& choice2 = second-choice
答案 0 :(得分:0)
这是我如何处理这种情况..
不要将您的选择视为ID。对所有选择选项使用单个类,然后使用基于类的选择器将.change()绑定到所有选择。如果这样做,您可以迭代X个选择,使用它们的id作为查询参数变量,并将它们的值用作每个查询值。我在jsfiddle上为你创建了一个快速演示。我还在下面发布了你的代码....
<div>
<select class="php-options" id='first-choice' name='first-choice'>
<option value='1-0'>choose</option>
<option value='1-1'>1-1</option>
<option value='1-2'>1-2</option>
<option value='1-3'>1-3</option>
<option value='1-4'>1-4</option>
<option value='1-5'>1-5</option>
</select>
</div>
<div>
<select class="php-options" id='second-choice' name='second-choice'>
<option value='2-0'>choose</option>
<option value='2-1'>2-1</option>
<option value='2-2'>2-2</option>
<option value='2-3'>2-3</option>
<option value='2-4'>2-4</option>
<option value='2-5'>2-5</option>
</select>
</div>
<div id="request-url"></div>
$(document).ready(function(){
//treat your select options with classes,
//bind change event on each select
$('.php-options').change(function(e){
var urlValues = [],
parameterArgs = "";
//loop selects to build parameters
$('.php-options').each(function(i,v){
var optValue = $(this).val(),
optId=$(this).attr('id'),
parameter = ""+optId+"="+optValue;
urlValues.push(parameter);
});
//build parameter string
parameterArgs =urlValues.join("&");
//output query
$('#request-url').text('getter.php?'+parameterArgs);
});
});