简体   繁体   English

Javascript / PHP中的HTML转义/编码

[英]HTML Escaping/Encoding in Javascript/PHP

I have multiple pages of html code saved into a database. 我有多页html代码保存到数据库中。 I want a file to be able to flip through each of these pages without reloading. 我希望文件能够翻转每个页面而无需重新加载。

I created a PHP file to pull all the pages into a database. 我创建了一个PHP文件,将所有页面都拉入数据库。

The page shows the first page and navigation buttons. 该页面显示第一页和导航按钮。

There is also javascript to put all the other pages into an array so I can quickly switch pages. 还有javascript将所有其他页面放入一个数组,以便我可以快速切换页面。

var pages = new Array();
<?php foreach ($coursePages as $page): ?>
    pages[pageCount] = "<?php echo ($page['body']) ?>";
    pageCount++;
<?php endforeach ?>

My problem is creating the javascript array. 我的问题是创建javascript数组。 How can I escape the data from the echo properly so it can eventually change the page content using the following: 如何正确地从回显中转义数据,以便最终使用以下内容更改页面内容:

$(document).ready(function() {
    $('.navNext, .navPrevious').click(function({
        if ($(this).hasClass('navNext')) {
            page++;
            if (page > pageCount) {
                page = 0;
            }
        } else {
            page--;
            if (page < 0) {
                page = 0;
            }
        }

        $('.page').html(pages[page]);
    }))
});

you can use this function to escape js values: 你可以使用这个函数来转义js值:

function js_escape_string($str)
{
    $str = str_replace("\\", "\\\\", strval($str));
    $str = str_replace("'", "\\'", $str);
    $str = str_replace("\r", "\\r", $str);
    $str = str_replace("\n", "\\n", $str);
    $str = str_replace("\t", "\\t", $str);
    $str = str_replace("</script>", "</'+'script>", $str);
    return $str;
}

NOTE: use single quote ' around JS values, like: 注意:围绕JS值使用单引号,例如:

<script>
var a = '<?php echo js_escape_string(....); ?>';
</script>

Anytime you send values dynamically from PHP to JavaScript, you can simply use json_encode(). 无论何时您将值从PHP动态发送到JavaScript,您都可以使用json_encode()。 It will always produce valid JavaScript and handle all data types. 它将始终生成有效的JavaScript并处理所有数据类型。 Example: 例:

<script>
    var a = <?php echo json_encode($var)?>;
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM