javascript - 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();
}
});
});
});
解决方案
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>
推荐阅读
- c++ - 在 C++ 中调整用户输入
- c# - HTTP POST 上的 XMLHttpRequest 错误(POST 工作,返回失败)
- swiftui - Apple Watch 模态表中的 SwiftUI 图像
- python-3.x - 进程以退出代码 -1073741819 (0xC0000005) 和 python 崩溃完成
- r - R中按组对异常值进行Winsorization
- c# - WPF WebView2 - 如何启用安全浏览
- flutter - 带有复选框的自定义下拉菜单
- javascript - React - 遍历状态数组但没有结果
- javascript - 如何在 jQuery 中向 websocket 发送登录请求
- javascript - 功能编辑后放大 Window PC 上的推送崩溃