首页 > 解决方案 > Ajax 调用仅适用于表的第一行,不适用于下一行

问题描述

在我看来,我正在显示一个表格,并且在表格中我强输入了下拉列表,当您更改所选项目时,它通过 ajax 调用调用 getPrice(int product_id) 函数并返回所选项目的价格,但它仅适用于第一行。

HTML

 <tr class="tr_clone" id="1">
     <td>
        @Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { @class = "form-control sel"}
     </td>
     <td class="product_price" id="product_price" style="text-align: center; font-size: 16px;">@Html.DisplayFor(model => model.product_price, "", "") </td></tr>

<tr class="tr_clone1" id="2">
     <td>
     @Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { @class = "form-control sel"})
     </td>
     <td class="product_price" id="product_price1" style="text-align: center; font-size: 16px;">@Html.DisplayFor(model => model.product_price, "", "")</td></tr>

阿贾克斯调用

 $(function () {
        $('#product_id').change(function () {
            $.ajax({
                type: "POST",
                url: "/Home/GetPrice",
                datatype: "Json",
                data: { product_id: $('#product_id').val() },
                success: function (data) {
                    document.getElementById('product_price').innerHTML = data;
                    multiply();
                },
                error: function (data = 0) {
                    document.getElementById('product_price').innerText = 0;
                    multiply();
                }
            });
        });
    });

标签: javascriptasp.netajaxasp.net-mvc

解决方案


html

   @Html.DropDownListFor(model => model.product_id, ViewBag.ProductList as SelectList, "--select product--", new { @class = "form-control sel", @onchange = "gg(this)" })

ajax 调用

 <script>
    function gg(x) {
        $.ajax({
            type: "POST",
            url: "/Home/GetPrice // GetPrice is name of actionmathod of controller",
            datatype: "Json",
            data: { product_id: $(x).val() },
            success: function (data) {
                //your code here
            },
            error: function () {
                // your code here
            }
        });
    }
</script>

推荐阅读