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

ajax delete data javascript

May 09, 2023 am 09:16 AM

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>
Copy after login

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));
}
Copy after login

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);
    });
  });
};
Copy after login

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()
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles