how to modify Request.JSON to satisfy cross domain security
I'm using mootools to request json from my web handler and this is working fine from the same machine. I've read in places about need for a callback to satisfy cross domain issues but unsure how to apply this. I'd like to run t开发者_如何学运维his code from another domain.
var input = [];
var jsonRequest = new Request.JSON({
url: "http://www.mysite.com.au/GetImages.ashx?p=2",
onSuccess: function (result) {
for (var i = 0; i < result.length; i++) {
// alert(result[i].MediaPath);
var s = result[i].MediaPath.split('|');
for (var j = 0; j < s.length; j++) {
// alert(s[j]);
input.push(s[j]);
}
}
}
}).get();
cheers!
One solution is to use JSONP.
Here is the client-side code you would use:
<script>
function onSuccess(result) {
for (var i = 0; i < result.length; i++) {
// alert(result[i].MediaPath);
var s = result[i].MediaPath.split('|');
for (var j = 0; j < s.length; j++) {
// alert(s[j]);
input.push(s[j]);
}
}
}
</script>
<script src="http://www.mysite.com.au/GetImages.ashx?p=2&callback=onSuccess" ></script>
<!-- !!! Notice that the src now has a "callback" paramater which the client is passing to the server. -->
Here is what the server would respond with:
onSuccess(
{
'your':'json',
'data':'here'
}
)
The trick which makes this work is that the server no longer technically returns json data. Instead, it will return json data wrapped by a javascript function (which the client-side code will define) that will automatically be executed by the browser because that's what browsers do with tags.
If you need to have it dynamically gathered, then you can have javascript code create a script element, add the url as the 'src' attribute, then append the script tag to body to have the browser execute it. This hack is a very standard way to dynamically download scripts. MooTools might already have a way to do this.
Downside with my suggestion: it is no longer asynchronous.
Another potential solution is to have your server proxy the json requests from other sites. I am unfamiliar with how this would be done, but I think that the SOAP protocol implements this.
精彩评论