MySQL과 JavaScript를 사용하여 간단한 온라인 편집기 기능을 구현하는 방법

王林
풀어 주다: 2023-09-21 11:01:20
원래의
1461명이 탐색했습니다.

MySQL과 JavaScript를 사용하여 간단한 온라인 편집기 기능을 구현하는 방법

"MySQL과 JavaScript를 사용하여 간단한 온라인 편집기 기능을 구현하는 방법"이라는 제목처럼

인터넷의 급속한 발전으로 인해 점점 더 많은 응용 프로그램에서 사용자가 텍스트, 코드를 작성하고 편집할 수 있도록 지원하는 온라인 편집기가 필요합니다. 그리고 각종 서류. 이 기사에서는 MySQL과 JavaScript를 사용하여 간단한 온라인 편집기 기능을 구현하는 방법을 소개하고 구체적인 코드 예제를 제공합니다.

1. 데이터베이스 디자인

온라인 편집 기능은 사용자가 생성한 파일을 저장해야 하므로 관련 정보를 저장하기 위한 데이터베이스가 필요합니다. MySQL을 데이터베이스로 사용하고, MySQL에서 "files"라는 데이터베이스를 생성하고, 데이터베이스에 "documents"라는 테이블을 생성합니다. 테이블의 구조는 다음과 같습니다.

CREATE TABLE `documents` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `title` VARCHAR(255) NOT NULL,
  `content` TEXT NOT NULL,
  PRIMARY KEY (`id`)
);
로그인 후 복사

2. 백엔드 구현

  1. 백엔드 로직을 처리하기 위해 "server.js"라는 파일을 만듭니다. 먼저 필요한 라이브러리와 모듈을 소개해야 합니다. 코드는 다음과 같습니다.
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();
로그인 후 복사
  1. 라우팅 및 처리 기능을 정의합니다. 우리는 다음 경로를 정의합니다:
  • POST /documents: 새 문서를 만드는 데 사용됩니다.
  • GET /documents: 모든 문서를 얻는 데 사용됩니다.
  • GET /documents/:id: ID를 기반으로 지정된 문서를 얻는 데 사용됩니다.
  • PUT /documents/:id: 지정된 문서를 업데이트하는 데 사용됩니다.
  • DELETE /documents/:id: 지정된 문서를 삭제하는 데 사용됩니다.

코드는 다음과 같습니다.

// 创建文档
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');
});
로그인 후 복사

3. 프론트 엔드 구현

  1. 프런트 엔드 디스플레이 및 상호 작용을 위해 "editor.html"이라는 파일을 만듭니다. 먼저 HTML 페이지를 만들고 필요한 라이브러리와 파일을 소개해야 합니다. 코드는 다음과 같습니다.
<!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>
로그인 후 복사
  1. 프론트 엔드 로직을 처리하기 위해 "editor.js"라는 파일을 만듭니다. 코드는 다음과 같습니다.
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();
  }
});
로그인 후 복사

4. 테스트 및 실행

  1. 명령줄에 프로젝트 폴더를 입력하고 필요한 종속성을 설치합니다.
$ npm install express body-parser mysql
로그인 후 복사
  1. 백엔드 서버 시작:
$ node server.js
로그인 후 복사
  1. 에서 열기 온라인 편집기 기능을 사용하려면 browser editor.html 파일을 사용하세요.

요약:

이 글에서는 추가, 삭제, 수정, 검색과 같은 기본 작업을 포함하여 MySQL 및 JavaScript를 통해 간단한 온라인 편집기 기능을 구현합니다. 프런트엔드와 백엔드를 분리해 프런트엔드는 Vue.js를 사용해 간단한 인터랙티브 인터페이스를 구현하고, 백엔드는 Express와 MySQL을 사용해 데이터를 처리한다.

위는 MySQL과 JavaScript를 사용하여 간단한 온라인 편집기 기능을 구현하는 방법에 대한 자세한 소개와 코드 예제입니다. 이 기사가 온라인 편집기를 이해하고 사용하는 데 도움이 되기를 바랍니다.

위 내용은 MySQL과 JavaScript를 사용하여 간단한 온라인 편집기 기능을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!