MVC中动态加载脚本文件

MVC中动态加载脚本文件

本文介绍了在ASP.NET MVC中动态加载脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET MVC.我有一个视图,可在部分中加载部分视图的内容.

I'm using ASP.NET MVC. I have a view that loads contents of a partial view in a section.

问题是部分视图中包含一些脚本引用.因此,当我在主页上加载该局部视图的内容时,脚本标签将被删除以保护视图免受脚本注入攻击.

Problem is that partial view has some script references in it. so when I load contents of that partial view in the main page, script tags get removed to protect view against script injection attacks.

我尝试了多种方法来从部分页面内容中过滤脚本标记并分别加载主题,但是我没有成功.

I have tried different ways to filter script tags out of partial page content and load theme separately but I was unsuccessful.

例如,我尝试过滤脚本标记并将其附加到主页的开头,如下所示:

For example I have tried to filter script tags and append them in the head of main page like this :

 var scripts = $(content).filter('script');
 $(scripts).each(function() {
 $('head').append($(this));

我也尝试过使用$ .getscript加载那些脚本.该函数可以很好地执行,但不会出现在chrome开发人员工具的页面资源中.而且我无法在这些脚本中使用函数.

I have also tried to load those scripts using $.getscript. The function gets executed nicely but they don't appear in page resource in chrome developer tools. and I cannot use functions inside those scripts.

我该如何实现?

推荐答案

您可以将脚本的所有引用移至主视图,也可以使用$ .ajax"dataType as script"动态加载脚本:

You can move all references of script to Main view or you can use $.ajax "dataType as script" to load script dynamically:

http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests

$.ajax({
  dataType : 'script',
  url : 'http://example.com',
  success : function() {
  console.log(a);
  }
});

这篇关于在ASP.NET MVC中动态加载脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:32