2015-08-21 46 views
0

我想做一個Ajax調用來獲取數據和修改DOM。如何讓ajax調用獲取部分視圖包含javascript?

這裏是我的控制器/動作看起來像

[HttpGet] 
public ActionResult Index(int id) 
{ 
// some code 
return PartialView(Custom Object); 
} 
here is my Index View looks like 

@Model CustomObject 
    @foreach(loop thru Model) 
    { 
// add some other elements 
} 
if(Model.Count==0){ 
<script>some script</script> 
}else{ 
<script>variable = '<div></div>'</script> 
} 

這裏是主視圖代碼

<script>var variable ='';</script> 
<script>$('element').html(variable)</script> 
<tbody id="tbodyId"> 
@RenderAction("Index"); 
<tbody> 

這裏是我的AJAX調用。我試圖做

function test(id){ 
$.ajax({ 
type:'Get', 
url:'/Home/Index?id='+id, 
datatype:'html' 
}) 
.done(function(data){ 
$('#tbodyId').html(data); 
}); 
} 

我的問題是從上面的ajax調用它不是從局部視圖追加腳本元素。

我試過不同的方式從JavaScript方面。但是,我不知道我是否正確地做到了這一點。所以,我需要一些線索的建議。

這是我嘗試的另一種方式。但沒有運氣

var scriptElement = document.createElement('script'); 
      scriptElement.innerHTML = $('#tbodyId').last().html(); 
      document.getElementById('tbodyId').appendChild(scriptElement); 

任何幫助,將不勝感激。謝謝!!

+0

不要!一個部分不應該包含腳本 –

回答

1

嘗試

var scriptElement = document.createElement('script'); 
scriptElement.textContent = $('#tbodyId').last().html(); 
// remove `#` from selector 
document.getElementById('tbodyId').appendChild(scriptElement); 
+0

沒有運氣與上述change.BTW'#'是代碼中的拼寫錯誤。我編輯了我的帖子。 –

相關問題