循环形式的 AJAX 请求

我想知道如何在循环表单中单独发出ajax请求,当我单击指定的行删除按钮时,它能够发送异步删除请求。当我使用 jquery 单击按钮时,不确定如何分配身份。


foreach(var item in Model){

  <form>

    <input type="text" id="id" name="id" value="item.id"/>

    <input type="button" id="btn" name="submit" value="Delete"/>

  </form>

}


<script>

  $("#btn").click(function(){

          // alert the id value

      });

</script>


一只甜甜圈
浏览 107回答 2
2回答

慕娘9325324

你可以尝试使用foreach(var item in Model){&nbsp; <form>&nbsp; &nbsp; <input type="text" id="id" name="id" value="item.id"/>&nbsp; &nbsp; <input type="button" class="btn" data-id="item.id" name="submit" value="Delete"/>&nbsp; </form>}<script>&nbsp; $(".btn").click(function(){&nbsp; &nbsp; // alert the id value&nbsp; &nbsp; alert($(this).attr("data-id"))&nbsp; });</script>

喵喵时光机

我找到了基于 Agus Friasana 方法的解决方案:$(".btn").click(function () {&nbsp; &nbsp; &nbsp; &nbsp; // to skip the alert from parent modal button&nbsp; &nbsp; &nbsp; &nbsp; if ($(this).attr("data-id") != undefined) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert($(this).attr("data-id").toString());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: "your url" + $(this).attr("data-id").toString(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: "DELETE",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; dataType: "text",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('success');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; error: function () {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert('fail')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript