使用jQuery和ASP.NET MVC嵌入小部件

我需要一些建议,以便在开发可嵌入的小部件时使用最佳方法,我的网站用户可以使用它来在他们的网站上显示我们的内容。

假设我们有一些内容使用jQuery插件进行渲染,我们希望为客户提供一种简单的方法将其嵌入到他们的网站中。

一种选择可能是使用IFrame,但我们知道这是非常侵入性的并且存在一些问题。 我也想知道你对此的看法。

另一种方法可能是给出这样的代码,以显示第23项:

并以某种方式(这里需要帮助……)创建wdg.js服务器端脚本以在DIV内部注入内容,jQuery,所需的插件。

这看起来更有希望,因为用户可以在一定程度上定制DIV的样式,并且不需要IFRAME。 但是哪个是在ASP.NET MVC中执行此操作的最佳和更有效的方法?

当然还有许多其他方法可以实现我们的需求。

JSONP是一种方法。 首先编写一个自定义ActionResult ,它将返回JSONP而不是JSON,这将允许您解决跨域Ajax限制:

 public class JsonpResult : JsonResult { public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; if (!string.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { var request = context.HttpContext.Request; var serializer = new JavaScriptSerializer(); if (null != request.Params["jsoncallback"]) { response.Write(string.Format("{0}({1})", request.Params["jsoncallback"], serializer.Serialize(Data))); } else { response.Write(serializer.Serialize(Data)); } } } } 

然后你可以写一个返回JSONP的控制器动作:

 public ActionResult SomeAction() { return new JsonpResult { Data = new { Widget = "some partial html for the widget" } }; } 

最后人们可以使用jQuery在他们的网站上调用此操作:

 $.getJSON('http://www.yoursite.com/controller/someaction?jsoncallback=?', function(json) { $('#someContainer').html(json.Widget); } ); 

如果用户不想在他们的站点上包含jQuery,您可以在您的站点上编写包含jQuery的JavaScript代码并执行之前的getJSON调用,这样人们只需要在站点中包含一个JavaScript文件,如示例所示。


更新:

正如评论部分所述,这是一个示例,说明如何从脚本动态加载jQuery。 只需将以下内容放入您的JavaScript文件中:

 var jQueryScriptOutputted = false; function initJQuery() { if (typeof(jQuery) == 'undefined') { if (!jQueryScriptOutputted) { jQueryScriptOutputted = true; document.write(""); } setTimeout("initJQuery()", 50); } else { $(function() { $.getJSON('http://www.yoursite.com/controller/someaction?jsoncallback=?', function(json) { // Of course someContainer might not exist // so you should create it before trying to set // its content $('#someContainer').html(json.Widget); } ); }); } } initJQuery();