加载一个PHP文件并根据选择设置变量


Loading a PHP file and set variable based on selection

我需要根据用户在一个或多个选择字段中选择的内容使用jquery加载PHP文件的内容。

I can use…

$("#first-choice").change(function() {
    $("#second-choice").load("getter.php?choice=" + $("#first-choice").val() );
});

…当'first-choice'字段由用户设置时,创建变量'choice'

但是,如果我想使用基于两个下拉选择器的2个变量,设置变量'choice'(基于#first-choice的选择)和choice2(基于#second-choice的选择)。

我想加载一个PHP文件比如getter。PHP ?choice=first-choice&choice2=second-choice

我是这样处理这种情况的

不要把你的选择当作id。对所有选择选项使用单个类,然后使用基于类的选择器将.change()绑定到所有选择。如果这样做,您可以遍历X个选择,使用它们的id作为查询参数变量,并将它们的值作为每个查询值。我在jsfiddle上为你做了一个快速的演示。我还在下面为您发布了代码....

这是我对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);        
});

});

相关文章: