如何重新加载Thymeleaf表而无需退出页面?

时间:2020-07-24 09:11:59

标签: javascript html jquery css thymeleaf

下面是我的HTML和JavaScript代码,我使用百里香叶来动态显示表格内容。 如您所见,通知值是否为1,更改按钮已禁用,其CSS已更改。但是当它的值是其他值时,用户可以单击该按钮。用户单击按钮后,将调用worksomething()函数。现在,我想要的是如果用户获得成功响应,而无需重新加载页面,则应该禁用附加到所选ID的按钮,并且还应该更改它的CSS,例如当notify的值为1时。

function worksomething(orderId){
  $.ajax({
    url  : "/myirl/"+ orderId,
    type : 'GET',
    contentType : "application/json",
    dataType : "JSON",
    success: function (response) {
      alert("Disabled");
    },
    error: function (response) {
      alert("work Failed");
    }
  });
}
<table class="table" data-table ="all-orders" id="all-orders" role="grid">
     <thead>
        <tr>
            <th>ID</th>
            <th>Actions</th>
        </tr>
     </thead>
     <tbody>
        <tr th:each="order : ${orders}">
            <td>
                <button class="btn btn-link" th:text="${order?.orderId}"></button>
            </td>
            <td>
                <button type="button" class="btn btn-warning btn-md"
                            th:disabled="${(order?.notified)} == 1"
                            th:style="${(order?.notified) == 1 ? 'background-color: red;border-color:red;' : 'background-color: #eea236;border-color:#eea236;'}"
                            th:onclick="|worksomething('${order?.orderId}')|">
                Change</button>
            </td>
      </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:1)

最好使用jQuery之类的Javascript库将JS事件与HTML关联。这样可以使代码更加清晰。

<table class="table" data-table ="all-orders" id="all-orders" role="grid">
     <thead>
        <tr>
            <th>ID</th>
            <th>Actions</th>
        </tr>
     </thead>
     <tbody>
        <tr th:each="order : ${orders}">
            <td>
                <button class="btn btn-link" th:text="${order?.orderId}"></button>
            </td>
            <td>
                <button type="button" class="btn btn-warning btn-md change-btn"
                            th:disabled="${(order?.notified)} == 1"
                            th:style="${(order?.notified) == 1 ? 'background-color: red;border-color:red;' : 'background-color: #eea236;border-color:#eea236;'}"
                   the:attrs="order-id=${order?.orderId}">
                Change</button>
            </td>
      </tr>
    </tbody>
</table>

使用jQuery的javascript是:

$(function(){
  $(".change-btn").on('click', function(event){
    var ordered = $(this).attr('order-id');
    var myButton = $(this);
    $.ajax({
      url  : "/myirl/"+ orderId,
      type : 'GET',
      contentType : "application/json",
      dataType : "JSON",
      success: function (response) {
        alert("Disabled");
        $(myButton).prop('disabled', true);
        //to remove disabled:
        //$(myButton).prop('disabled', false);
      },
      error: function (response) {
        alert("work Failed");
      }
    });
  });
});