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

发布于 2024-08-22 07:48:08 字数 607 浏览 5 评论 0原文

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

假设我们有一些内容使用 jQuery 插件进行渲染,我们想要给出我们的客户可以轻松地将其嵌入到他们的网站中。

一种选择是使用 IFrame,但正如我们所知,这是相当侵入性的并且存在一些问题。我也想知道你对此的看法。

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

<DIV id="mysitewidget23"><script src="http://example.com/scripts/wdg.js?id=23" /></DIV>

并且以某种方式(此处需要帮助...)创建 wdg.js 服务器端脚本以在 DIV 内注入内容、jQuery、所需的插件。

这看起来更有前途,因为用户可以在一定程度上自定义 DIV 的样式,并且不需要 IFRAME。但在 ASP.NET MVC 中哪种方法最好、更有效?

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

I need some advice for the best approach to use in developing embeddable widgets that my site users could use to show our content on their site.

Let's say we have some content which uses a jQuery plugin to be rendered, and we want to give our customers an easy way to embed it in their websites.

One option could be of using an IFrame, but as we know this is quite invasive and has some problems. I'd like to know your opinion on that, too.

Another approach could be giving a code like this, to show item #23:

<DIV id="mysitewidget23"><script src="http://example.com/scripts/wdg.js?id=23" /></DIV>

And somehow (help needed here...) creating the wdg.js server-side script to inject content, jQuery, needed plugins, inside the DIV.

This looks more promising, since the user can customize to a certain extent the style of the DIV, and no IFRAME is needed. But which is the best and more efficient way to do this in ASP.NET MVC?

There are of course many other approaches to achieve what we need.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不疑不惑不回忆 2024-08-29 07:48:08

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,您可以在您的网站上编写 JavaScript 代码,该代码将包含 jQuery 并执行之前的 getJSON 调用,这样人们只需包含站点中的单个 JavaScript 文件,如您的示例所示。


更新:

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

var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (!jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></scr" + "ipt>");
        }
        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();

JSONP is one way to do this. You start by writing a custom ActionResult that will return JSONP instead of JSON which will allow you to work around the cross-domain Ajax limitation:

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));
            }
        }
    }
}

Then you could write a controller action that returns JSONP:

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

And finally people can call this action on their sites using jQuery:

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

If users don't want to include jQuery on their site you might write JavaScript code on your site that will include jQuery and perform the previous getJSON call, so that people will only need to include a single JavaScript file from the site as in your example.


UPDATE:

As asked in the comments section here's an example illustrating how to load jQuery dynamically from your script. Just put the following into your JavaScript file:

var jQueryScriptOutputted = false;
function initJQuery() {
    if (typeof(jQuery) == 'undefined') {
        if (!jQueryScriptOutputted) {
            jQueryScriptOutputted = true;
            document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></scr" + "ipt>");
        }
        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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文