如何将数据发布到后端服务器以存储到数据库中? [英] How to POST data to a backend server to store into database?
本文介绍了如何将数据发布到后端服务器以存储到数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将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.
推荐答案
您将需要:
- 使用
JavaScript
从 - 将其包含在您的POST请求中.
- 在
PHP
中捕获并处理该请求,以将其存储在数据库中.
div
提取数据
- Extract the data from the
div
usingJavaScript
- Include it in your POST request.
- 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:
- 将零件
$('#myContent').text()
更改为$('#myContent').html()
. - 删除
htmlspecialchars(...)
方法的用法(例如$content = $_POST['myContent'];
).
- Change the part
$('#myContent').text()
to$('#myContent').html()
. - Remove the
htmlspecialchars(...)
method usage (e.g.$content = $_POST['myContent'];
).
这篇关于如何将数据发布到后端服务器以存储到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文