javascript - JQuery Cross-Domain .load() (self-constructing widget) -
i'm creating widget people use on websites, keep widget future-proof, want self constructing using external javascript.
so widget code ask people put on websites like:
<div id="my_widget"></div> <script type="text/javascript" src="http://www.external-domain.com/mywidget.js"></script>
mywidget.js
use jquery's .load()
populate #my_widget
div iframe.
problem doesn't work....
what need do?
(note dont want have iframe in code give customers)
it depends on url specifying in load
function. if url not hosted on same domain executes page containing script won't work due same origin policy restriction. 1 possible workaround make cross domain ajax calls use json-p if have control on server side script used in load
function.
here's idea behind json-p:
- you provide server side script hosted on domain return jsonp formatted response. domain domain have full control.
- this server side script called domain b using ajax.
let's suppose http://domaina.com/myscript?jsoncallback=foo
returns following response:
foo({ result: '<strong>hello world</strong>' });
now inside mywidget.js
call script:
$.getjson('http://domaina.com/myscript?jsoncallback=?', function(data) { $('#my_widget').html(data.result); });
all left tell users include mywidget.js
script , provide placeholder id="my_widget"
host results (you generate placeholder in success callback).
remark: when using jsonp limited requests only. means there's limit in size of request can send.
Comments
Post a Comment