Home > Database > Mysql Tutorial > body text

How to use MySQL and JavaScript to implement a simple online editor function

王林
Release: 2023-09-21 11:01:20
Original
1461 people have browsed it

How to use MySQL and JavaScript to implement a simple online editor function

For example, "How to use MySQL and JavaScript to implement a simple online editor function"

With the rapid development of the Internet, more and more applications need to be online Editor to support users in writing and editing text, code, and various files. This article will introduce how to use MySQL and JavaScript to implement a simple online editor function and provide specific code examples.

1. Database design

The online editor function needs to store files created by users, so a database is needed to store related information. We use MySQL as the database, create a database named "files" in MySQL, and create a table named "documents" in the database. The structure of the table is as follows:

CREATE TABLE `documents` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(255) NOT NULL,
  `content` TEXT NOT NULL,
  PRIMARY KEY (`id`)
);
Copy after login

2. Backend Implementation

  1. Create a file named "server.js" to handle the back-end logic. First, we need to introduce the necessary libraries and modules. The code is as follows:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'files'
});

connection.connect();
Copy after login
  1. Define routing and processing functions. We define the following routes:
  • POST /documents: used to create new documents;
  • GET /documents: used to obtain all documents;
  • GET /documents/:id: used to obtain the specified document based on ID;
  • PUT /documents/:id: used to update the specified document;
  • DELETE /documents/:id: used to delete the specified document.

The code is as follows:

// 创建文档
app.post('/documents', (req, res) => {
  const { title, content } = req.body;
  const query = `INSERT INTO documents (title, content) VALUES ('${title}', '${content}')`;

  connection.query(query, (error, results) => {
    if (error) throw error;

    res.json({ id: results.insertId });
  });
});

// 获取所有文档
app.get('/documents', (req, res) => {
  connection.query('SELECT * FROM documents', (error, results) => {
    if (error) throw error;

    res.json(results);
  });
});

// 根据ID获取文档
app.get('/documents/:id', (req, res) => {
  const { id } = req.params;
  const query = `SELECT * FROM documents WHERE id = ${id}`;

  connection.query(query, (error, results) => {
    if (error) throw error;

    if (results.length > 0) {
      res.json(results[0]);
    } else {
      res.status(404).json({ error: 'Document not found' });
    }
  });
});

// 更新文档
app.put('/documents/:id', (req, res) => {
  const { id } = req.params;
  const { title, content } = req.body;
  const query = `UPDATE documents SET title = '${title}', content = '${content}' WHERE id = ${id}`;

  connection.query(query, (error, results) => {
    if (error) throw error;

    res.json({ success: true });
  });
});

// 删除文档
app.delete('/documents/:id', (req, res) => {
  const { id } = req.params;
  const query = `DELETE FROM documents WHERE id = ${id}`;

  connection.query(query, (error, results) => {
    if (error) throw error;

    res.json({ success: true });
  });
});

// 启动服务器
app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});
Copy after login

3. Front-end implementation

  1. Create a file named "editor.html" for front-end display and interaction . First, we need to create an HTML page and introduce the necessary libraries and files. The code is as follows:
<!DOCTYPE html>
<html>
<head>
  <title>Online Editor</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
  <div id="app">
    <h1>Online Editor</h1>
    <form @submit.prevent="saveDocument">
      <input type="text" v-model="title" placeholder="Title" required>
      <textarea v-model="content" placeholder="Content" required></textarea>
      <button type="submit">Save</button>
    </form>
    <ul>
      <li v-for="document in documents" :key="document.id">
        <a :href="'/documents/' + document.id">{{ document.title }}</a>
        <button @click="deleteDocument(document.id)">Delete</button>
      </li>
    </ul>
  </div>
  <script src="editor.js"></script>
</body>
</html>
Copy after login
  1. Create a file named "editor.js" to handle the front-end logic . The code is as follows:
new Vue({
  el: '#app',
  data: {
    title: '',
    content: '',
    documents: []
  },
  methods: {
    async saveDocument() {
      try {
        const response = await axios.post('/documents', {
          title: this.title,
          content: this.content
        });
        this.documents.push({ id: response.data.id, title: this.title });
        this.title = '';
        this.content = '';
      } catch (error) {
        console.error(error);
      }
    },
    async deleteDocument(id) {
      try {
        await axios.delete(`/documents/${id}`);
        this.documents = this.documents.filter(document => document.id !== id);
      } catch (error) {
        console.error(error);
      }
    },
    async fetchDocuments() {
      try {
        const response = await axios.get('/documents');
        this.documents = response.data;
      } catch (error) {
        console.error(error);
      }
    }
  },
  mounted() {
    this.fetchDocuments();
  }
});
Copy after login

4. Testing and running

  1. Enter the project folder on the command line and install the necessary dependencies:
$ npm install express body-parser mysql
Copy after login
  1. Start the backend server:
$ node server.js
Copy after login
  1. Open the editor.html file in the browser to start using the online editor function.

Summary:

This article implements a simple online editor function through MySQL and JavaScript, including basic operations such as addition, deletion, modification, and query. By separating the front and back ends, the front end uses Vue.js to implement a simple interactive interface, and the back end uses Express and MySQL to process data.

The above is a detailed introduction and code example on how to use MySQL and JavaScript to implement a simple online editor function. I hope this article can help you understand and use the online editor.

The above is the detailed content of How to use MySQL and JavaScript to implement a simple online editor function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!