JQuery Cross-Domain .load() (self-constructing widget)

*爱你&永不变心* 提交于 2019-12-21 06:54:07

问题


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.

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 would then use jquery's .load() to populate the #my_widget div with an iframe.

Problem is this doesn't work....

what do i need to do?

(note i dont want to have the iframe in the code i give to my customers)


回答1:


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.

Here's the idea behind JSON-P:

  1. You provide a server side script hosted on Domain A which will return JSONP formatted response. Domain A is your domain for which you have full control.
  2. This server side script could be called from Domain B using AJAX.

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

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

Now inside mywidget.js you could call this script:

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

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).

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.




回答2:


You have total control of their page since you're executing your code on their site.

You can create iframes document.createElement("iframe"), inject it anywhere on the page document.getElementById("my_widget").appendChild(iframe) and do whatever else you feel like.

One thing to be careful with this is to not clutter their namespaces... avoid any usual namespace and make up your own (__my_widget or whatever else is weird). And try to keep the namespaces counts as low as 1, or even none if possible.

Don't use load, use an iframe if you're just trying to load html from your site.



来源:https://stackoverflow.com/questions/3889001/jquery-cross-domain-load-self-constructing-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!