我需要用最好的方法在开发嵌入式小工具,我的网站的用户可以用它来展示我们在其网站上的内容了一些建议。

比方说,我们有一些内容它采用了的jQuery插件要呈现的,我们想要一个简单的方法给我们的客户在他们的网站中嵌入它。

一种选择是使用iframe的,但我们知道这是相当侵入性的,有一些问题。我想知道你对这种看法了。

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

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

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

这看起来更有前途的,因为用户可以自定义要在一定程度上DIV的风格,并没有IFRAME是必要的。但是,这是在ASP.NET MVC做到这一点最好的和更有效的方式?

当然还有很多其他的方法来实现我们所需要的。

有帮助吗?

解决方案

JSONP 是做到这一点的一种方式。你开始通过编写自定义的ActionResult 那将返回,而不是JSON JSONP,这将使您能够解决跨域阿贾克斯不限于:

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();
scroll top