如何使用 TinyMCE、jQuery 和 PDO 提交 HTML 表单? (完整代码)
How to submit HTML form using TinyMCE, jQuery and PDO? (full code)
$_POST['reply']
变量包含 html 标签,如 <p>text goes here</p>
,但我无法将其插入数据库。对于 reply
我使用 TinyMCE 并且当我不使用它时(输入为无标签)如 text goes here
然后它被正确插入。
我在这里错过了什么?
try {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("INSERT INTO replies(article_id, comment) VALUES (:article_id, :comment)");
$stmt->bindParam(':article_id', $article_id, PDO::PARAM_INT);
$stmt->bindParam(':comment', $_POST['reply'], PDO::PARAM_STR);
if($stmt->execute()) {
echo 'success';
}
$db = null;
} catch(PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
表单代码如下:
<form class="comment-form">
<div class="form-input">
<input type="hidden" name="post_id" value="<?= $row['id']; ?>" />
</div>
<div class="form-input">
<textarea name="reply" id="elm1" rows="8" placeholder="Your comment here" ></textarea>
</div>
<div class="form-input">
<input type="Submit" class="btn btn-primary" id="submit" value="SEND" />
</div>
</form>
<script type="text/javascript">
$(function(){
$(".comment-form").submit(function(event){
event.preventDefault();
$("#results")
.show();
$.post('add-it.php', $(".comment-form").serialize(), function(data) {
$('#submit')
.hide();
$('#results')
.html(data)
.fadeIn('slow');
});
});
});
</script>
您可以使用
$pdo->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);
而不是 bindParam
这应该插入您的 html 代码。
并且您应该将 post 设置为表单的方法
<form action="#" method="post" class="comment-form">
</form>
下一个你应该删除你的 javascript 代码并在没有和有正常形式的情况下测试它来测试你的问题。
然后主要问题是你 $_POST
变量是空的,这不是 PDO 问题。
最后一个,如果您使用 Ajax 发送请求,则必须致电
tinyMCE.triggerSave();
http://www.tinymce.com/wiki.php/API3:method.tinymce.triggerSave
函数 ins TinyMCE 否则你的 post 变量是空的。
由于使用AJAX,需要在TinyMCE中手动触发保存功能。这需要在您发送请求之前完成。
$("#results").show();
tinyMCE.triggerSave(); // <--- Add this here
$.post('add-it.php'....
而且这绝对与PDO无关。在将记录插入 table.
之前,您可以简单地执行 print_r($_POST)
查看是否有数据
我认为您的问题是 TinyMCE 不会自动将其更改绑定到文本区域。您需要在提交处理程序中调用 tinyMCE.triggerSave()
。参见 When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database。
我附上了完整的代码示例,我可以确认它是否有效。
<?php
define('DB_DRIVER', 'mysql');
define('DB_DATABASE', 'test');
define('DB_SERVER', '127.0.0.1');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
try {
$db = new PDO(
DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER,
DB_USER,
DB_PASSWORD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("
INSERT INTO replies(article_id, comment)
VALUES (:article_id, :comment)");
$stmt->bindValue(':article_id', $_POST['article_id'], PDO::PARAM_INT);
$stmt->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);
if ($stmt->execute()) {
echo 'success';
}
$db = null;
} catch (PDOException $e) {
trigger_error('Error occurred while trying to insert into the DB:'
. $e->getMessage(), E_USER_ERROR);
}
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>tinymce.init({selector: 'textarea'});</script>
<form class="comment-form">
<div class="form-input">
<input type="hidden" name="article_id" value="1"/>
</div>
<div class="form-input">
<textarea name="reply" id="elm1"></textarea>
</div>
<div class="form-input">
<input type="Submit" class="btn btn-primary" id="submit" value="SEND"/>
</div>
</form>
<div id="results">
Results
</div>
<script type="text/javascript">
$(function () {
$(".comment-form").submit(function (event) {
event.preventDefault();
$("#results").show();
tinyMCE.triggerSave();
$.post('add-it.php', $(".comment-form").serialize(),
function (data) {
$('#submit').hide();
$('#results').html(data).fadeIn('slow');
});
});
});
</script>
CREATE TABLE `replies` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`article_id` int(11) DEFAULT NULL,
`comment` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
我已经使用了你的代码并进行了相当多的尝试,我想我已经能够为你整理它,希望如此,我已经更改了 $(".comment-form").serialize()
以手动添加数据。我还添加了 tinymce.get('elm1').getContent()
因为这将检索 TinyMCE 文本区域中的数据。
<script type="text/javascript">
$(function(){
$(".comment-form").submit(function(event){
event.preventDefault();
$("#results")
.show();
$.post('add-it.php', {
post_id: $( '.post_id' ).val(),
reply: tinymce.get('elm1').getContent()
}, function(data) {
$('#submit')
.hide();
$('#results')
.html(data)
.fadeIn('slow');
});
});
});
</script>
我认为这个问题HTML Tags stripped using tinyMCE. Try to use a simple textarea and check if html is posted correctly and saved to the database. This way you will have another clue if this is a fault server-side or client-side. Also try this http://jsfiddle.net/PGtPa/172/提供了一个解决方案的想法来检查你的序列化输出。
textarea_value -> <p>do this do that</p>
serialized_value -> %3Cp%3Edo+this+do+that%3C%2Fp%3E
jQuery serialize 是 url-encoding 输出,因此请检查该部分是否与 tinymce 设置有冲突。此外,如果 mod_security 给您带来问题,您可以尝试在发布之前使用 javascript 对 textarea 值进行 base64 编码,并在服务器端进行 base64 解码以获取您的真实值。对于 base64 和 javascript 检查这个 https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding 如果你使用 utf8,它有一个很好的例子。
$_POST['reply']
变量包含 html 标签,如 <p>text goes here</p>
,但我无法将其插入数据库。对于 reply
我使用 TinyMCE 并且当我不使用它时(输入为无标签)如 text goes here
然后它被正确插入。
我在这里错过了什么?
try {
$db = new PDO(DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER, DB_USER, DB_PASSWORD, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("INSERT INTO replies(article_id, comment) VALUES (:article_id, :comment)");
$stmt->bindParam(':article_id', $article_id, PDO::PARAM_INT);
$stmt->bindParam(':comment', $_POST['reply'], PDO::PARAM_STR);
if($stmt->execute()) {
echo 'success';
}
$db = null;
} catch(PDOException $e) {
trigger_error('Error occured while trying to insert into the DB:' . $e->getMessage(), E_USER_ERROR);
}
表单代码如下:
<form class="comment-form">
<div class="form-input">
<input type="hidden" name="post_id" value="<?= $row['id']; ?>" />
</div>
<div class="form-input">
<textarea name="reply" id="elm1" rows="8" placeholder="Your comment here" ></textarea>
</div>
<div class="form-input">
<input type="Submit" class="btn btn-primary" id="submit" value="SEND" />
</div>
</form>
<script type="text/javascript">
$(function(){
$(".comment-form").submit(function(event){
event.preventDefault();
$("#results")
.show();
$.post('add-it.php', $(".comment-form").serialize(), function(data) {
$('#submit')
.hide();
$('#results')
.html(data)
.fadeIn('slow');
});
});
});
</script>
您可以使用
$pdo->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);
而不是 bindParam
这应该插入您的 html 代码。
并且您应该将 post 设置为表单的方法
<form action="#" method="post" class="comment-form">
</form>
下一个你应该删除你的 javascript 代码并在没有和有正常形式的情况下测试它来测试你的问题。
然后主要问题是你 $_POST
变量是空的,这不是 PDO 问题。
最后一个,如果您使用 Ajax 发送请求,则必须致电
tinyMCE.triggerSave();
http://www.tinymce.com/wiki.php/API3:method.tinymce.triggerSave
函数 ins TinyMCE 否则你的 post 变量是空的。
由于使用AJAX,需要在TinyMCE中手动触发保存功能。这需要在您发送请求之前完成。
$("#results").show();
tinyMCE.triggerSave(); // <--- Add this here
$.post('add-it.php'....
而且这绝对与PDO无关。在将记录插入 table.
之前,您可以简单地执行print_r($_POST)
查看是否有数据
我认为您的问题是 TinyMCE 不会自动将其更改绑定到文本区域。您需要在提交处理程序中调用 tinyMCE.triggerSave()
。参见 When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database。
我附上了完整的代码示例,我可以确认它是否有效。
<?php
define('DB_DRIVER', 'mysql');
define('DB_DATABASE', 'test');
define('DB_SERVER', '127.0.0.1');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
try {
$db = new PDO(
DB_DRIVER . ":dbname=" . DB_DATABASE . ";host=" . DB_SERVER,
DB_USER,
DB_PASSWORD,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db->prepare("
INSERT INTO replies(article_id, comment)
VALUES (:article_id, :comment)");
$stmt->bindValue(':article_id', $_POST['article_id'], PDO::PARAM_INT);
$stmt->bindValue(':comment', $_POST['reply'], PDO::PARAM_STR);
if ($stmt->execute()) {
echo 'success';
}
$db = null;
} catch (PDOException $e) {
trigger_error('Error occurred while trying to insert into the DB:'
. $e->getMessage(), E_USER_ERROR);
}
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<script>tinymce.init({selector: 'textarea'});</script>
<form class="comment-form">
<div class="form-input">
<input type="hidden" name="article_id" value="1"/>
</div>
<div class="form-input">
<textarea name="reply" id="elm1"></textarea>
</div>
<div class="form-input">
<input type="Submit" class="btn btn-primary" id="submit" value="SEND"/>
</div>
</form>
<div id="results">
Results
</div>
<script type="text/javascript">
$(function () {
$(".comment-form").submit(function (event) {
event.preventDefault();
$("#results").show();
tinyMCE.triggerSave();
$.post('add-it.php', $(".comment-form").serialize(),
function (data) {
$('#submit').hide();
$('#results').html(data).fadeIn('slow');
});
});
});
</script>
CREATE TABLE `replies` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`article_id` int(11) DEFAULT NULL,
`comment` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
我已经使用了你的代码并进行了相当多的尝试,我想我已经能够为你整理它,希望如此,我已经更改了 $(".comment-form").serialize()
以手动添加数据。我还添加了 tinymce.get('elm1').getContent()
因为这将检索 TinyMCE 文本区域中的数据。
<script type="text/javascript">
$(function(){
$(".comment-form").submit(function(event){
event.preventDefault();
$("#results")
.show();
$.post('add-it.php', {
post_id: $( '.post_id' ).val(),
reply: tinymce.get('elm1').getContent()
}, function(data) {
$('#submit')
.hide();
$('#results')
.html(data)
.fadeIn('slow');
});
});
});
</script>
我认为这个问题HTML Tags stripped using tinyMCE. Try to use a simple textarea and check if html is posted correctly and saved to the database. This way you will have another clue if this is a fault server-side or client-side. Also try this http://jsfiddle.net/PGtPa/172/提供了一个解决方案的想法来检查你的序列化输出。
textarea_value -> <p>do this do that</p>
serialized_value -> %3Cp%3Edo+this+do+that%3C%2Fp%3E
jQuery serialize 是 url-encoding 输出,因此请检查该部分是否与 tinymce 设置有冲突。此外,如果 mod_security 给您带来问题,您可以尝试在发布之前使用 javascript 对 textarea 值进行 base64 编码,并在服务器端进行 base64 解码以获取您的真实值。对于 base64 和 javascript 检查这个 https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding 如果你使用 utf8,它有一个很好的例子。