Can a Client Link to My JavaScript, Hosted on a Different Domain?
Is it possible for me to supply a client with a snippet of HTML which contains a reference to a javascript file that I host? They want to paste this HTML into their CMS, so th开发者_开发技巧at when their page loads, it'll load our content.
I was under the impression that there was cross domain security preventing this from being possible.
What if, instead of linking to the JavaScript, I gave them the snippet of HTML with the JavaScript already included
so instead of
<div>
<!-- link to js -->
</div>
I gave them
<div>
$.get(/*url to my content*/);
</div>
Would that work?
You could use JSONP to simulate cross domain AJAX calls (works only with GET requests as internally it uses a script
tag):
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data) {
$.each(data.items, function(i,item) {
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
}
);
Is it possible for me to supply a client with a snippet of HTML which contains a reference to a javascript file that I host?
Yes. The src of script elements has no same origin limits.
$.get(/*url to my content*/);
XMLHttpRequests still do have same origin limits. XHR can only fetch from the domain of the page, not the script.
The HTML <script>
tags are exempt from the same origin policy, so if your client links to your JavaScript file with <script>
tags, you will not have any problems. (Source)
Referencing a javascript file from a different domain is no problem. This is not cross site scripting, it's simply a cross site HTTP request. This is used a lot, e.g. by Google's JavaScript API Loader.
精彩评论