A series of ignorant JS cross domain scripting questions!!

KevySaysBeNice

[H]ard|Gawd
Joined
Dec 7, 2001
Messages
1,452
Stupid/simple question, I know, but, here goes:

Say I have a webpage:

http://first.website.com/stuff.html which contains:
Code:
<ul><li>some</li><li>stuff</li></ul>

Is it possible to do this on a different website:
http://second.differentcompletely.com/getstuff.html
Code:
$.get(
"http://first.website.com/stuff.html",
    function(data) {
        alert(data);
        $('#lol').html(data);
    }
);

It doesn't SEEM possible... but is it?


fake edit:

So, as I see it, the ONLY three options to get data cross domain is:

1) Write a local server side page that takes in a parameter, which will load the contents of a remote page and then spit it back out, avoiding the entire client side cross scripting issue all together

2) <EDIT> I had mentioned using getJSON, because I thought it was somehow magic, but in reality i raelize that getJSON is just implementing $.ajax - so now I'm totally confused why this works:
Code:
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';

			// Request that YSQL string, and run a callback function.
			// Pass a defined function to prevent cache-busting.
			$.getJSON( yql, cbFunc );

Even though it's cross site... Is it because JSON is being returned, and as long as it's JSON it's all good in the hood? </EDIT>


OK, so, now here are some questions:

1) Am I right? Are those really my one three options?

2) Why can I use getJSON cross-domain, but something like .ajax or .get won't work cross domain? I realize that these are all jQuery functions, but if I were to implement ajax myself with the XMLHttpRequest object (or whatever), would I have this problem? I'm guessing this is a browser thing, that blocks cross domain calls. But again, why does getJSON seem to be able to access cross domain "stuff"? <EDIT>SEE EDIT ABOVE</EDIT>

3) BONUS QUESTION to show my complete ignorance: why, when you use google analytics, is cross site scripting not an issue? When you do something like event tracking, isn't that making ajax calls to google, on a different domain? And getting some data back? Or is it simply posting data, and nothing is being returned?

Thanks <3
 
If I remember right, I believe jQuery is using JSONP to implement getJSON. Basically, instead of performing an actual XMLHttpRequest (which is limited to the domain) it creates a new <script> element with the src attribute set to your request. Since a script element is not limited to the domain, this works (...with JSON).

Your best bet is to use a proxy (like you mention) from your server. Not only will this have the same effect as a remote XMLHttpRequest, but it will allow you to filter the returned data to ensure it is safe for your script to read.
 
Back
Top