简体   繁体   中英

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.

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. 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.

I tried different ways from javascript side. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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