<?php
$regex = "/\<script(.*?)?\>(.|\\n)*?\<\/script\>/i";
$scripts = array();
$phpuphtml="<div>test</div><script>alert(\"test\")</script><script>alert(\"test2\")</script>";
preg_match_all($regex, $phpuphtml, $scripts); //抽取js到$scripts
$phpuphtml=rawurlencode(preg_replace($regex,'',$phpuphtml)); //删除js代码并格式化
$scriptshtml="";
foreach ($scripts[0] as $script){ //遍历累加js
$scriptshtml.=$script;
}
$scriptshtml=rawurlencode($scriptshtml); //格式代码
?>
<script>
require(["jquery"],function($){ //引用jquery
$divhtml= $("<div></div>");
$divhtml.html(unescape("<?= $phpuphtml ?>"));
$divscripts= $("<div></div>");
$divscripts.html(unescape("<?= $scriptshtml ?>"));
$('body').append($divhtml); //添加HTML
$('body').append($divscripts); //添加js
$divscripts.trigger('contentUpdated'); //运行js
});
</script>
注意:目前只支持普通js代码执行问题,magento :type="text/x-magento-init" 类型的还无法执行。