根据选择框 ajax php mysql 填充文本框

Populate a textbox based on selectbox ajax php mysql

我有一个问题。所以我尝试根据选择框填充文本框的值。我的 HTML:

<form id="form_gift" action="myAction" method="post">
    <div class="form-group">
        <label for="">Gift</label>
        <select id="statusSelect" name="{{ form_gift.gift.name }}" class="form-control" onChange="getPrix()">
            {% for key,category in form_gift.gift.choices %}
                <option value="{{ key }}">
                    {{ category }}
                </option>
            {% endfor %}
        </select>
    </div>
    <div class="form-group">
        <label class="control-label" for="">Price</label>
        <input type="text" id="{{ form_gift.prix.name }}" name="{{ form_gift.prix.name }}" value="" placeholder="" class="form-control" required="required"/>
    </div>
</form>
<script>
    function getPrix() {
        var selectedId =   $("#statusSelect option:selected").val(),
            url_deploy = "http://"+window.location.hostname+"/getPrice";
        $.ajax({
            url: url_deploy,
            type: "POST",
            async: true,
            data: { id:selectedId},
            dataType: 'json',
            success: function (result) {
                $('#prix').val(result.Value);
            }
        });
    }
</script>

我的PHP:

public function getPrix()
{
    if (isset($_POST['id']))
    {
        $iIdGift = $_POST['id'];
    }

    $o_Article = Article::find($iIdGift);
    $prix = $o_Article->articlePrice();
    error_log(print_r($prix,true), 3, "/var/tmp/error.log");
    return json_encode($prix);
}

我测试了 PHP 代码,它工作正常。问题是当我试图填充选择框时,我认为是在成功方法中。请帮帮我!提前致谢!

鉴于返回的格式 JSON:

the format of json is like this: {"id":"59.90"}

您需要使用 id 键访问该值,试试这个:

success: function (result) {
    $('#prix').val(result.id);
}
<input type="text" id="{{ form_gift.prix.name }}" name="{{ form_gift.prix.name }}" value="" placeholder="" class="form-control txtPrix" required="required"/>


   success: function (result) {
        $('.txtPrix').val(result.id);
    }