Не удается запустить javascript с помощью Ext.Ajax в Sencha-Touch2?

Я использую htmlPanel.js в Sencha-Touch, который обсуждался на форуме здесь для отображения локального HTML-контента. Я могу загрузить html-контент с помощью обычного html-тега, но не javascript.

Ниже приведен htmlPanel.js, который я использовал:

Ext.define('HTMLPanel', {
    extend: 'Ext.Panel',


// We are using Ext.Ajax, so we should require it
    requires: ['Ext.Ajax'],
    config: {
        listeners: {
            activate: 'onActivate'
        },


// Create a new configuration called `url` so we can specify the URL
        url: null        
    },


    onActivate: function(me, container) {
        Ext.Ajax.request({
// we should use the getter for our new `url` config
            url:    'htmlTest.html',//this.getUrl(),
            method: "GET",
            success: function(response, request) {
// We should use the setter for the HTML config for this
//Ext.Msg.alert('Alert', 'Success!!!', Ext.emptyFn);    
                me.setHtml(response.responseText);                
            },
            failure: function(response, request) {
//Ext.Msg.alert('Alert', 'Failure!!!', Ext.emptyFn);    
                me.setHtml("failed -- response: " + response.responseText);
            }
        });
    }
});

Ниже мой htmlTest.html:

<!DOCTYPE html>
<html>
    <body>

        <canvas id="myCanvas">Your browser does not support the HTML5 canvas tag.</canvas>

        <script type="text/javascript" charset="utf-8">
            var c=document.getElementById('myCanvas');
            var ctx=c.getContext('2d');
            ctx.fillStyle='#FF0000';
            ctx.fillRect(0,0,640,1280);
        </script>

        <h1>This is some text in a paragraph.</h1>

    </body>
</html>

И ниже мой index.js:

Ext.application({
    name: 'SampleLoad',
    launch: function () {
        //loadURL('htmlTest.html');
        Ext.Viewport.add({
                        url:    'htmlTest.html',
            xclass: "HTMLPanel",

        });

        // Add the new HTMLPanel into the viewport so it is visible
        Ext.Viewport.add(HTMLPanel);
    }
});

Я могу видеть текст «Некоторый текст здесь», но не холст, который я пытался создать с помощью javascript.

Есть ли какой-либо конфиг, который нужно указать? Или любая другая причина?

Спасибо.


person user1686573    schedule 20.09.2012    source источник


Ответы (1)


Проблема в том, что HTML внедряется в DOM, но скрипты не выполняются. Это относится к присваиванию innerHtml и, вероятно, также к setHtml().

Вы можете решить эту проблему, явно выполнив сценарии в отображаемом элементе сразу после вставки HTML. Тогда ваш htmlPanel.js будет выглядеть так:

...
// We should use the setter for the HTML config for this
//Ext.Msg.alert('Alert', 'Success!!!', Ext.emptyFn);    
                me.setHtml(response.responseText);  
                var scriptArray = me.renderElement.dom.getElementsByTagName("script");   
                for(var i=0;i<scriptArray.length;i++) {  
                   eval(scriptArray[i].text);  
                }              
            },
...
person Pum Walters    schedule 23.09.2012
comment
+1 Хорошее решение! Но есть ли более элегантный способ добиться этого? Без необходимости извлекать JavaScript? - person Shaunak; 28.09.2012