【问题标题】:PHP removing everything after HTML tagsPHP 删除 HTML 标记后的所有内容
【发布时间】:2014-01-02 21:41:01
【问题描述】:

我有一个这样的 contenteditable div:

<form>
    <div name="new_post" class="post" contenteditable="true"></div>
    <button type="submit">Submit</button>
</form>

contenteditable div 允许 bolditalic 标签,但 没有其他标签

我的问题是,如果用户键入Hello there &lt;u&gt;world&lt;/u&gt;! 之类的内容,它将在数据库中保存为Hello there。好像把标签后面的东西都删掉了,不知道为什么。

我正在使用 AJAX 和 PHP 来处理帖子,所以这是其余的代码。

阿贾克斯:

$(document).ready(function() {
    $(document).on("submit", "form", function(event) {
        event.preventDefault();
        alert($('.post').html()); // added this to debug it. This prints "Hello there &lt;u&gt;world&lt;/u&gt;!"
        $.ajax({
            url: 'php/post.php',
            type: 'POST',
            dataType: 'json',
            data: $(this).serialize() + "&post_field=" + $('.post').html(),
            success: function(data) {
                alert(data.message);
            }
        });
    });
});

PHP:

<?php
    $post = $_POST["post_field"];

    // query to insert post into database goes here

    $array = array('message' => $post);

    echo json_encode($array);
?>

请帮忙!

【问题讨论】:

  • 去掉不需要的标签的代码在哪里?
  • 这很奇怪。没有,但它正在删除它。
  • 可能是你的网络服务器模块(比如 apache 的 mod-security)
  • 在连接到序列化数据之前是否需要对 HTML 进行 URL 编码?
  • 为什么人们从来不让 jQuery 做序列化?试图超越 jQuery 永远行不通

标签: javascript php ajax jquery


【解决方案1】:

变化:

$('.post').html()

到:

encodeURIComponent($('.post').html())

HTML 字符需要在 URL 参数中编码。

【讨论】:

  • 这解决了我原来的问题,但是,我现在有另一个问题。我已将$post = strip_tags($post, "&lt;b&gt;&lt;i&gt;"); 添加到PHP 代码中,以便它删除除粗体和斜体之外的所有标记。但是,如果用户在邮箱中输入Hello there &lt;u&gt;world&lt;/u&gt;!,它仍然会输出Hello there &lt;u&gt;world&lt;/u&gt;!。为什么以及如何解决这个问题?
  • 新问题应单独发布。
  • @Bagwell,这已经完成了。如果您遇到新问题,请先尝试自己解决它们,然后再将它们扔给 SO
猜你喜欢
  • 2011-06-05
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-12-02
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多