【问题标题】:How to call Ajax from Javascript function如何从 Javascript 函数调用 Ajax
【发布时间】:2018-06-02 05:21:03
【问题描述】:

我在 html 表中的 <td> 中有一个删除按钮,并附加了一个 onclick() 函数。如何从此函数调用 ajax,即我想获取 <tr> 中的值并发布到 URL。

    <script>
        function deleteRow(btn) {
            var row = btn.parentNode.parentNode;
            id = row.cells[0].textContent;
            //call ajax, pass id as data
        }
    </script>

  <body>
    <table>
      <tr>
        <th>Id</th>
        <th>Lastname</th>
        <th>Firstname</th>
        <th></th>
      </tr>
      <tr>
        <td>122</td>
        <td>Jackson</td>
        <td>Evans</td>
        <td><button type="button" onclick="deleteRow(this)">Delete row</button></td>
      </tr>
    </table>
  </body>

【问题讨论】:

标签: javascript


【解决方案1】:

你可以在这里使用一些东西。关注 JavaScript 部分的 cmets:

// Run at document load.
$(function () {
  // Get the button. Make it unobtrusive as there could be more.
  // Execute this on click event.
  $(".del-btn").click(function () {
    // Fire an AJAX call.
    $.post("/path/to/delete", {id: $(this).closest("tr").find("td:first").text()}, function () {
      $(this).closest("tr").fadeOut();
    });
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<table>
  <tr>
    <th>Id</th>
    <th>Lastname</th>
    <th>Firstname</th>
    <th></th>
  </tr>
  <tr>
    <td>122</td>
    <td>Jackson</td>
    <td>Evans</td>
    <td><button type="button" class="del-btn">Delete row</button></td>
  </tr>
</table>

正如 Sid 所说,我还要求您使用 data-* 属性,并且不要完全依赖 DOM 来获取数据。这将需要您进行更改:

// Run at document load.
$(function () {
  // Get the button. Make it unobtrusive as there could be more.
  // Execute this on click event.
  $(".del-btn").click(function () {
    // Fire an AJAX call.
    $.post("/path/to/delete", {id: $(this).closest("tr").data("id")}, function () {
      $(this).closest("tr").fadeOut();
    });
  });
});
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<table>
  <tr>
    <th>Id</th>
    <th>Lastname</th>
    <th>Firstname</th>
    <th></th>
  </tr>
  <tr data-id="122">
    <td>122</td>
    <td>Jackson</td>
    <td>Evans</td>
    <td><button type="button" class="del-btn">Delete row</button></td>
  </tr>
</table>

【讨论】:

  • 对数据使用DOM元素是一种反模式,我宁愿建议将数据传递给方法,或者使用数据属性
  • 您正在对执行删除的服务的性质做出一些重大假设。如果它是一个 RESTful 服务,则该方法将是 DELETE,而不是 POST。也许您可以等到问题得到澄清后再回答?
  • 是的@MikeMcCaughan
  • @Sid 同意使用data-* 属性是使用它的好方法。我已经在答案中更新了它,并给了你应得的学分,老板。也看看我之前的评论。谢谢。
  • 这仍然是一个糟糕问题的答案。您基本上已经为他们编写了 OP 的代码,并回答了许多其他问题的副本。我从未说过您的代码不起作用,但我确实要求您等到问题得到澄清。因此,您做出了一个成功的猜测,并使该站点更加混乱,重复出现。恭喜?
【解决方案2】:

我宁愿不直接给出答案。使用 jquery 的示例代码是:

$("selector").click(function(){
    $.post("/your/path", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 2013-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多