php - 使用AJAX选择下拉列表,自动填充textarea

时间:2013-01-20 09:22:45

标签: php ajax

我有一个名为customers_shipto的表,其中包含列(ID,shiptonick,地址)

我需要使用与AJAX相关的特定记录的地址列中的数据自动填充textarea“shipto”

我的选择看起来像这样

<select name="shiptonick" id="shiptonick">
    <option value="">Click Here to Change Ship To</option>
    <?
    $sql = "SELECT * FROM customers_shipto WHERE customer_id = '$customer_id' ORDER BY shiptonick ASC"; 
    $result = mysql_query($sql);
    while($row = mysql_fetch_array($result)) {
    ?>
    <option value="<?=$row['ID']?>"><?=$row['shiptonick']?></option>
    <? } ?>
</select>

和textare看起来像这样

<textarea name="shipto" id="shipto" cols="30" rows="5"></textarea>

我假设我会调用像getaddress.php这样的文件来将结果返回给AJAX

$sql = "SELECT * FROM customers_shipto WHERE ID = '$ID'"; 
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['address'];
}

更新:以下是我认为接近我想要的AJAX的一些示例代码,但我没有调用“提交”,而是需要为该特定选择调用“onChange”,以便执行此代码。

            <script type"text/javascript">
            $(document).ready(function(){
            $("form#submit").submit(function() {
            // we want to store the values from the form input box, then send via ajax below
            var ID = $('#ID').attr('value');
            var shiptonick = $('#shiptonick').attr('value');
            $.ajax({
            type: "POST",
            url: "includes/getaddress.php?",
            data: "ID="+ ID+
                "&shiptonick="+ shiptonick,
            success: function(data){
                //Return address here and place in textarea njavascript code
            }
            });
            return false;
            });
            });
        </script>
我结束了吗? :)

1 个答案:

答案 0 :(得分:1)

使用ajax调用函数绑定选择onchange,将地址填充到textarea

$("#shiptonick").change(function(){

    var id = $(this).val(); //the selected id from shiptonick

    $.ajax({
             type: 'POST',
             url: 'the php page that returns address based on id',
             data: {ID: id},
             success: function(data){
                 if(data != null)
                    $("#shipto").val(data);
             }
           });    

});