Home >Web Front-end >Front-end Q&A >ajax delete data javascript

ajax delete data javascript

WBOY
WBOYOriginal
2023-05-09 09:16:37772browse

With the rapid development of the Internet and the continuous advancement of IT technology, ajax technology is used in many web applications to implement the partial refresh function, thus improving the user experience and page response speed. In some scenarios where data needs to be deleted, ajax can also be used to perform the deletion operation, so that there is no need to refresh the entire page, and users can also see the deletion effect immediately on the page.

This article will introduce how to use javascript and ajax technology to delete data.

Step one: Write HTML file

First, create an HTML file locally or on the server, and write basic HTML code and related styles. Set a button on the page to trigger the delete operation, and each data entry that needs to be deleted has a corresponding delete button. In addition, a data table needs to be rendered to display the data, as shown in the following code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Ajax删除数据示例</title>
    <style>
      table {
          border-collapse: collapse;
          margin:auto;
      }

      th, td {
        padding: 10px;
        border: 1px solid black;
      }

      button {
          background-color: #4CAF50;
          color: white;
          padding: 10px;
          border: none;
          cursor: pointer;
          margin-top: 15px;
      }

      button:hover {
          opacity: 0.8;
      }
    </style>
  </head>
  <body>
    <h2>Ajax删除数据示例</h2>

    <table>
      <thead>
        <tr>
          <th>用户名</th>
          <th>邮箱</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>张三</td>
          <td>zhangsan@gmail.com</td>
          <td><button class="delete" data-id="1">删除</button></td>
        </tr>
        <tr>
          <td>李四</td>
          <td>lisi@gmail.com</td>
          <td><button class="delete" data-id="2">删除</button></td>
        </tr>
        <tr>
          <td>王五</td>
          <td>wangwu@gmail.com</td>
          <td><button class="delete" data-id="3">删除</button></td>
        </tr>
      </tbody>
    </table>

    <button id="delete-all">删除所有数据</button>

    <script src="js/ajax.js"></script>
    <script src="js/main.js"></script>
  </body>
</html>

In the above code, we use a data table to display the data, and each row has a delete button. By setting the data-id attribute, you can know which piece of data you want to delete. Among them, the delete-all button can delete all data at once.

Step 2: Write javascript code

Next, introduce an ajax.js file and a main.js file into the HTML file, which are used to handle ajax requests and page interaction logic respectively.

The code of the ajax.js file is as follows:

function ajax(method, url, data, success, error) {
  let xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200 || xhr.status == 304) {
        success(xhr.responseText);
      } else {
        error(xhr.status);
      }
    }
  };
  xhr.send(JSON.stringify(data));
}

In the ajax.js file, we define an ajax function for sending requests and receiving responses. Among them, method represents the request method, url represents the requested URL, data represents the request parameters, success represents the callback function when the request is successful, and error represents the callback function when the request fails. This function uses the XMLHttpRequest object internally to send the request, sets the request parameters and callback function, and finally sends the request through the send method.

The next is the code of the main.js file, which is used to bind button events and handle page interactions:

function deleteData(id) {
  ajax(
    "DELETE",
    "/api/data/" + id,
    {}, // 请求参数
    function(responseText) {
      // 删除成功,刷新页面
      location.reload();
    },
    function(status) {
      // 请求失败
      console.log(status);
    }
  );
}

window.onload = function() {
  let deleteAllBtn = document.querySelector("#delete-all");
  let deleteBtns = document.querySelectorAll(".delete");
  // 删除所有数据
  deleteAllBtn.addEventListener("click", function() {
    ajax(
      "DELETE",
      "/api/data/all",
      {}, // 请求参数
      function(responseText) {
        // 删除成功,刷新页面
        location.reload();
      },
      function(status) {
        // 请求失败
        console.log(status);
      }
    );
  });
  // 删除单个数据
  deleteBtns.forEach(function(btn) {
    btn.addEventListener("click", function() {
      let id = this.getAttribute("data-id");
      deleteData(id);
    });
  });
};

In the main.js file, we use the window.onload event to bind Button events on the specified page. Among them, querySelectorAll and forEach methods are used to obtain all delete buttons and delete all data buttons respectively, and bind click events to them. When the user clicks the delete button, the deleteData function is called, which sends a DELETE request to delete the specified data entry.

Step 3: Write server-side code

Finally, write a RESTful API interface on the server side to provide support for deletion operations. Since different server-side languages ​​and frameworks implement different methods, here we only provide a pseudocode for reference:

import flask
app = flask.Flask(__name__)

@app.route('/api/data/<int:id>', methods=['DELETE'])
def delete_api(id):
   # 连接数据库并删除指定的数据
   return 'ok'

@app.route('/api/data/all', methods=['DELETE'])
def delete_all_api():
   # 连接数据库并删除所有数据
   return 'ok'

if __name__ == '__main__':
   app.run()

In the above pseudocode, we use Python's flask framework to build a simple API interface , where the data to be deleted is specified through the id parameter in the delete_api function, while all data is deleted in the delete_all_api function. Only a pseudo code is provided here, readers can write specific server-side code according to their actual situation.

Summary

This article introduces how to use javascript and ajax technology to delete data, and also provides a flask-based pseudocode for reference. In actual development, corresponding code needs to be written according to specific needs, and issues such as security, performance, and user experience need to be paid attention to. Through the reasonable use of ajax technology, we can provide users with a smoother and better WEB experience, and improve our own development efficiency and code quality.

The above is the detailed content of ajax delete data javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:css cancel centerNext article:css cancel center