JQuery Post转义提交HTML模板

3.5k 前端 , , 发表评论

最近遇到这样一个问题,在表单中有一个textarea文本框,用来保存HTML模板。

因为是HTML模板,所以会有<html><script>等标签,但是这样无法通过AJAX Post方式保存。

经过实验,<script是导致无法提交的根源。找到原因,解决办法就简单了,就是把<转义成HTML实体&lt;

最新说明:这个最后发现,是__POST被后台的PHP代码拦截了,所以不是客户端的问题,把PHP拦截代码去掉就可以了。

具体措施如下:

1 HTML表单

Form表单如下:

<form action="save.php" method="post">
    <textarea name="source"></textarea>
    <button type="submit">提交</button>
</form>

然后,在文本框中输入如下内容,

<!DOCTYPE html>
<html>
<head>
    <title>演示</title>
    <script type="text/javascript">
        alert("弹出框");
    </script>
</head>
<body>
     <div>演示</div>
</body>
</html>

再提交。

2 Post提交

JQuery Post提交代码如下:

$("form[method='post']").on('submit', function (e) {
    e.preventDefault();
    var form = $(this);

    $.post(
            form.attr("action"),
            form.serialize(),
            function (result) {
                $('.alert').html(result.msg).show().delay(1500).fadeOut();
                if (result.success) {
                    setTimeout(function () {
                        window.location.href = "index.php";
                    }, 1000);
                } else {
                    return false;
                }
            },
            'json'
    );
});

这样是无法提交的。

3 转义函数

我们需要先对HTML符号进行转义,函数如下:

// 转义字符为HTML实体,相当于PHP的htmlspecialchars()函数
function html_encode(str)
{
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/\"/g, "&quot;");
    return s;
}

// HTML实体转换为HTML标签,相当于PHP的htmlspecialchars_decode()函数
function html_decode(str)
{
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&quot;/g, "\"");
    return s;
}

4 转义后再提交

修改HTML代码,把textarea的name属性改成另外一个名称,如source改成html_source

<form action="save.php" method="post">
    <textarea name="html_source"></textarea>
    <button type="submit">提交</button>
</form>

然后就可以在post之前转义textarea内容,再提交source就可以了,如下:

$("form[method='post']").on('submit', function(e){
    e.preventDefault();
    var form = $(this);

    var html_source = encodeURIComponent(html_encode(form.find('textarea[name=html_source]').val()));
    form.find('textarea[name=html_source]').prop('disabled', true);

    $.post(
        form.attr("action"),
        form.serialize() + '&source=' + html_source,
        function (result) {
            $('.alert').html(result.msg).show().delay(1500).fadeOut();
            if(result.success) {
                setTimeout(function(){
                    window.location.href = "index.php";
                }, 1000);
            } else {
                form.find('textarea[name=html_source]').prop('disabled', false);
                return false;
            }
        },
        'json'
    );
});

这样就可以顺利提交了,下次PHP显示时,用 htmlspecialchars_decode() 函数解码就可以正常显示。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

昵称 *