如何将数据发布到后端服务器以存储到数据库中? [英] How to POST data to a backend server to store into database?

查看:178
本文介绍了如何将数据发布到后端服务器以存储到数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将div以下数据存储到我的数据库中.

I want to store below div data into my database.

<div id="myContent" contenteditable="true">This is a simple text</div>

给我任何示例,说明如何将这些数据发布到数据库中.

Give me any example how I can POST this data into a database.

推荐答案

您将需要:

  1. 使用JavaScript
  2. div提取数据
  3. 将其包含在您的POST请求中.
  4. PHP中捕获并处理该请求,以将其存储在数据库中.
  1. Extract the data from the div using JavaScript
  2. Include it in your POST request.
  3. Catch and handle the request in PHP to store it in the Database.

示例:

这是一个单独的 PHP 文件示例(没有刷新整个页面),但是您可能需要更改部分DATABASE_NAME_HERE以及root(这是用户名). /p>

Example:

This is a single PHP file sample (without full page refresh), but you may need to change the part DATABASE_NAME_HERE and also root (which is the user-name).

<?php
if (isset($_POST['submit'])) {
  // Escape possible HTML tags:
  $content = htmlspecialchars($_POST['myContent'], ENT_QUOTES | ENT_SUBSTITUTE);

  // Database connection.
  $db = new PDO('mysql:dbname=DATABASE_NAME_HERE', 'root', '');
  $db->query('CREATE TABLE IF NOT EXISTS `my_table` (id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL, text VARCHAR(1024))');

  // Storing new record.
  $query = $db->prepare('INSERT INTO my_table VALUES (NULL, :text)');
  $query->bindValue(':text', $content);
  if ($query->execute()) {
    $response = 'Successfully stored: ' . $content;
  }
  else {
    $response = 'Error: ' . join(' ', $query->errorInfo());
  }

  exit($response);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<title>My title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
    $('form#my_form_id').submit(function(e) {
      e.preventDefault();

      const content = $('#myContent').text();
      $.post('#', {submit: true, myContent: content}, function(response) {
        alert(response);
      });
    });
  });
</script>
</head>
<body>

<div id="center" style="text-align: center; margin-top: 150px;">
    <div id="myContent" contenteditable="true">This is simple text</div>

    <form id="my_form_id">
        <input name="username">
        <input type="submit" name="Send">
    </form>
</div>

</body>
</html>

注意:如果您想存储div的整个HTML,而不仅仅是上面的文本:

Note: if you want to store the entire HTML of the div and not just its text in above:

  1. 将零件$('#myContent').text()更改为$('#myContent').html().
  2. 删除htmlspecialchars(...)方法的用法(例如$content = $_POST['myContent'];).
  1. Change the part $('#myContent').text() to $('#myContent').html().
  2. Remove the htmlspecialchars(...) method usage (e.g. $content = $_POST['myContent'];).

这篇关于如何将数据发布到后端服务器以存储到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆