You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编辑帖子页用textarea替代input,如何将其内容保存为post_title?

如何提取textarea内容并保存为post_title

不管是原生开发还是用框架,核心逻辑都是先获取textarea的输入值,再提交到后端完成存储,以下是不同场景的具体实现方案:


一、前端获取textarea的值

1. 原生JavaScript实现

先给textarea设置id或name属性,方便定位元素:

<textarea id="postTitle" name="post_title" placeholder="输入帖子标题"></textarea>

然后通过JS获取内容并提交:

// 获取textarea元素
const titleTextarea = document.getElementById('postTitle');
// 提取输入内容
const postTitle = titleTextarea.value;

// 示例:用FormData提交到后端
const formData = new FormData();
formData.append('post_title', postTitle);

// 发送POST请求
fetch('/api/save-post', {
  method: 'POST',
  body: formData
}).then(res => {
  console.log('保存成功');
}).catch(err => {
  console.error('保存失败', err);
});

2. jQuery实现

如果项目用了jQuery,代码更简洁:

// 直接获取textarea的值
const postTitle = $('#postTitle').val();

// 提交到后端
$.post('/api/save-post', { post_title: postTitle }, function(response) {
  alert('标题已保存');
});

3. Vue/React框架实现

以Vue为例,用双向绑定直接绑定值:

<template>
  <textarea v-model="postTitle" placeholder="输入帖子标题"></textarea>
  <button @click="savePost">保存</button>
</template>

<script>
export default {
  data() {
    return {
      postTitle: ''
    }
  },
  methods: {
    savePost() {
      // 直接用this.postTitle拿到输入内容
      fetch('/api/save-post', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ post_title: this.postTitle })
      })
    }
  }
}
</script>

二、后端接收并保存

前端提交后,后端根据技术栈接收参数,再写入数据库:

1. PHP示例

// 接收前端传递的post_title
$postTitle = $_POST['post_title'];

// 示例:存入MySQL数据库(PDO方式)
$dsn = 'mysql:host=localhost;dbname=your_database';
$pdo = new PDO($dsn, 'username', 'password');

$stmt = $pdo->prepare("INSERT INTO posts (post_title) VALUES (?)");
$stmt->execute([$postTitle]);

echo '标题保存成功';

2. Node.js(Express)示例

const express = require('express');
const app = express();

// 解析表单数据
app.use(express.urlencoded({ extended: true }));

app.post('/api/save-post', (req, res) => {
  // 从请求体中获取post_title
  const postTitle = req.body.post_title;
  
  // 示例:存入MongoDB
  // const MongoClient = require('mongodb').MongoClient;
  // MongoClient.connect('mongodb://localhost:27017', function(err, client) {
  //   const db = client.db('your_database');
  //   db.collection('posts').insertOne({ post_title: postTitle });
  // });
  
  res.send('标题已保存');
});

app.listen(3000);

内容的提问来源于stack exchange,提问作者misticx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 11:20:58