简体   繁体   English

如何进行ajax调用以获取包含javascript的部分视图?

[英]how to make ajax call to get partial view contains javascript?

I am trying to make an ajax call to get data and to Modify DOM. 我正在尝试进行ajax调用以获取数据并修改DOM。

here is my controller/ action looks like 这是我的控制器/动作看起来像

   [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>
}

here is main view code 这是主视图代码

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

here is my Ajax Call. 这是我的Ajax电话。 I was trying to do 我正在尝试做

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

My issue is from the above ajax call it is not appending the script element from partial view. 我的问题是从上面的ajax调用来看,它不是从局部视图中追加脚本元素。

I tried different ways from javascript side. 我从JavaScript方面尝试了不同的方法。 But, im not sure whether im doing it right way or not. 但是,我不确定自己是否做对了。 So, i need some suggestions from leads. 因此,我需要潜在客户的一些建议。

here is the other way i tried. 这是我尝试过的另一种方式。 but no luck 但没有运气

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

any help would be appreciated. 任何帮助,将不胜感激。 Thanks!! 谢谢!!

Try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM