如何使用JavaScript提取多个脚本标记之间的代码块?

时间:2011-04-06 07:59:18

标签: javascript regex

我有以下功能,它通过AJAX从URI中提取 Javascript块,然后执行

function loadViewViaAjax(url, callbackOnSuccess) {
    Ext.Ajax.request({
        url: url,
        success: function(objServerResponse) {
            var responseText = objServerResponse.responseText;
            var scripts, scriptsFinder=/<script[^>]*>([\s\S]+)<\/script>/gi;
            while(scripts=scriptsFinder.exec(responseText)) {
                eval.call(window,scripts[1]);
            }
            if(typeof callbackOnSuccess != 'undefined') {
                callbackOnSuccess.call();
            }
        }
    });
}

例如,它会提取此文本,并在SCRIPT标记之间执行 eveything

<script type="text/javascript">
    clearExtjsComponent(targetRegion);
    var start_info_panel = new Ext.Panel({
        padding: 10,
        style: "margin: 10px",
        width: 300,
        html: '<h1>Html Item 1</h1>'
    });
    replaceComponentContent(targetRegion, start_info_panel);
</script>

如何更改loadViewViaAjax函数以便在多个脚本标记之间执行所有内容 ?,例如:

<script type="text/javascript">
    clearExtjsComponent(targetRegion);
    var start_info_panel = new Ext.Panel({
        padding: 10,
        style: "margin: 10px",
        width: 300,
        html: '<h1>Html Item 1</h1>'
    });
    replaceComponentContent(targetRegion, start_info_panel);
</script>
<script type="text/javascript">
    clearExtjsComponent(targetRegion_help);
    var help_panel = new Ext.Panel({
        padding: 10,
        style: "margin: 10px",
        width: 300,
        html: '<p>This is the help text.</p>'
    });
    replaceComponentContent(targetRegion_help, help_panel);
</script>

1 个答案:

答案 0 :(得分:3)

如果我正确阅读,这是懒惰量词的经典用法:

/<script[^>]*>([\s\S]+?)<\/script>/gi

另请参阅:What is the difference between .*? and .* regular expressions?