JQuery的跨域.load()(自建小部件) [英] JQuery Cross-Domain .load() (self-constructing widget)

查看:121
本文介绍了JQuery的跨域.load()(自建小部件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个小部件为人们在其网站上使用,但保持部件面向未来的,我想这是自我构建使用外部的JavaScript。

I'm creating a widget for people to use on their websites, however to keep the widget future-proof, i want it to be self constructing using an external javascript.

于是小部件codeI会要求人们把自己的网站会是这样的:

So the widget code i would ask people to put on their websites would be something like:

<div id="my_widget"></div>
<script type="text/javascript" src="http://www.external-domain.com/mywidget.js"></script>

mywidget.js 然后将使用jQuery的 .load()填充# my_widget div中的iframe。

mywidget.js would then use jquery's .load() to populate the #my_widget div with an iframe.

但问题是,这并不工作....

Problem is this doesn't work....

我需要什么做的?

(注意,我不希望有在codeI的iframe给我的客户)

推荐答案

这取决于你正在指定的负荷的功能是什么网址。如果该URL不是托管在一个执行包含此脚本不会因同一产地政策限制。一个可能的解决办法,使跨域ajax调用是使用 JSON-P 如果你有过被用在负载在服务器端脚本控制的功能。

It depends on what url you are specifying in the load function. If this url is not hosted on the same domain that executes the page containing this script won't work due to same origin policy restriction. One possible workaround to make cross domain ajax calls is to use JSON-P if you have control over the server side script which is used in the load function.

下面的背后JSON-P的理念是:

Here's the idea behind JSON-P:

  1. 您提供托管在域A的服务器端脚本,这将返回JSONP格式的响应。域A是域您拥有完全的控制。
  2. 在此服务器端脚本,可以从域B使用AJAX调用。

让我们假设 http://domainA.com/myscript?jsoncallback=foo 返回以下响应:

Let's suppose that http://domainA.com/myscript?jsoncallback=foo returns the following response:

foo({ result: '<strong>Hello World</strong>' });

现在里面 mywidget.js ,你可以调用这个脚本:

Now inside mywidget.js you could call this script:

$.getJSON('http://domainA.com/myscript?jsoncallback=?', function(data) {
    $('#my_widget').html(data.result);
});

所有剩下就是告诉用户包括 mywidget.js 脚本,并提供了一​​个占位符 ID =my_widget主办的结果(你甚至可以生成这个占位符的成功回调)。

All that is left is to tell the users include mywidget.js script and provide a placeholder with id="my_widget" to host the results (you could even generate this placeholder in the success callback).

备注:当使用JSONP你是仅限于GET请求。这意味着,有一个在可以发送请求的大小有限制。

Remark: When using JSONP you are limited to GET requests only. This means that there's a limit in the size of the request you can send.

这篇关于JQuery的跨域.load()(自建小部件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆