2012-09-20 19 views
3

我在論壇here中討論的Sencha-Touch中使用htmlPanel.js來顯示本地html內容。我能夠加載正常的HTML標籤,但不是JavaScript的HTML內容。無法在Sencha-Touch2中使用Ext.Ajax運行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創建的畫布。

是否有需要指定的配置?或者其他原因?

謝謝。

回答

5

問題是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); 
       }    
      }, 
... 
+0

+1很好的解決方案!但是,有沒有更好的方法來實現這一目標?無需提取JavaScript? – Shaunak