【问题标题】:Change a specific row data of a HTML table as well as database using AJAX call使用 AJAX 调用更改 HTML 表和数据库的特定行数据
【发布时间】:2016-04-14 07:50:25
【问题描述】:

我有一个这样的数据库表 -

----------------------------------| 身份证 |姓名 |状态 | ----------------------------------| 101 约翰 0 | | 102 罗伯特 1 | | 103 大卫 0 | ----------------------------------|

通过获取这个数据库,我正在创建一个 html 表(如下所示),其中每一行都有一个按钮来更改其在表和后端数据库中的当前状态。即 0 变为 1,1 变为 0。

<table>
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Status</th>
    <th>Action</th>
  </tr>
  <tr>
    <td>101</td>
    <td> John </td>
    <td> 0 </td>
    <td><button>Change Status</button> </td>
  </tr>
  <tr>
    <td>102</td>
    <td> Robert </td>
    <td> 1 </td>
    <td><button>Change Status</button> </td>
  </tr>
  <tr>
    <td>103</td>
    <td> David </td>
    <td> 0 </td>
    <td><button>Change Status</button></td>
  </tr>
</table>

这应该在不刷新页面的情况下完成。所以我认为我应该使用 ID 和该 ID 的状态对服务器进行 AJAX 调用。但我不明白该怎么做。

【问题讨论】:

  • 你应该自己试试。这是您使用 ajax 所做的非常基本的事情。只需在 data 中传递 id 和 status 并在使用成功回调的操作成功时在按钮旁边显示某种通知。

标签: jquery ajax html web html-table


【解决方案1】:

首先在button标签上添加一个数据属性并在其值中输出ID,并为当前状态创建另一个数据属性,使按钮标签看起来像这样:

<button data-id="5" data-status="0">Change Status</button>

然后使用 jQuery 的 ajax 方法将 Ajax 调用发送到服务器,如下所示:

$("button").click(function(e){
    e.preventDefault();
    data = {row_id: $(this).data('id'), current_status: $(this).data('status')};
    $.ajax({
        type : "post",
        data: data,
        url: "URL_TO_SERVER_FILE_WHICH_WILL_HANDLE DATA",
        success: function(result){
            // show message here and also change current status on data 
            // attribute of button and in the status column of table

        }
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2015-10-10
    相关资源
    最近更新 更多