如何通过jQuery传递选定的值

时间:2012-10-06 20:30:17

标签: php ajax jquery

我想使用jQuery在invoice.php文件中传递选定的值。在invoice.php文件上发送值后。我想在index.php页面上选中输入框显示invoice.php文件的echo结果。就像一个例子:如果有人选择项目,则在费率输入框上显示费率。这是我的代码和图片enter image description here

index.php文件代码:

<html>
    <head>
        <title>Invoice</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">

    $(document).ready(function(){
    $(".item").change(function(){
        calculate();
    });
});

function calculate() {

var item = [];
    $(".item").each(function() {
            var num=(this.value);
            item.push(num);
    });


    $('input[name=rate]').each(function(i){
        $.get(
            '/invoice_final_2.php',
            {'product':item[i]},
            function(data) {
                $(this).html(data);
            });
    });
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
</script>
<style type="text/css">
table
{
    border: 1px solid black;
    border-bottom: none;
    width: 300px;
}


td
{
    border-left: 1px solid black;
    border-bottom: 1px solid black;
    padding:5px 5px 5px 5px;
}
#first
{
    border-left: none;
    border-bottom: 1px solid black;
}
</style>
    </head>
    <body>
        <form method='post' name='form1' action='welcome.php'>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td id="first">Item</td>
                <td>Rate</td>
            </tr>
            <?php
            $num=4;
            for ($i=0; $i<$num; $i++)
            {
                echo "
                 <tr>
                 <td id='first'>
                 <select class='item' name='item'>
                 <option>Select one</option>
                 <option>Deluxe Plan</option>
                 <option>Premium Plan</option>
                 <option>Standard Plan</option>
                 <option>Economy Plan</option>
                 </select>
                </td>
                <td><input class='rate' type='text' name='rate'/></td>
               </tr>";
            }
            ?>
     </table>
</form>
</body>
</html>

invoice.php文件代码:

<?php
include "dbconnect.php";

$product=$_GET['product'];

$query="select * from item where item_name='$product'";
$result=mysql_query or die (mysql_error());
$row=mysql_fetch_assoc($result);
$rate=$row['rate'];

echo "$rate";

?>

1 个答案:

答案 0 :(得分:0)

我不确定您要实现的目标,但您不需要使用each并使用索引逐个发送值,您可以发送一次数组

function calculate() {
    var items = $(".item").map(function() {
          return this.value;
    }).get();

    $.get('/invoice_final_2.php',
        {'product': items },
        function(data) {
           //
        }
    );
}​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​