Skip to content

Instantly share code, notes, and snippets.

@jonleung
Created June 19, 2012 14:53
Show Gist options
  • Save jonleung/2954631 to your computer and use it in GitHub Desktop.
Save jonleung/2954631 to your computer and use it in GitHub Desktop.
Cross Domain Access in Javascript
function filterData(data){
// data = data.replace(/<?\/body[^>]*>/g,'');
// data = data.replace(/[\r|\n]+/g,'');
// data = data.replace(/<--[\S\s]*?-->/g,'');
// data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
// data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
// data = data.replace(/<script.*\/>/,'');
// data = data.replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
data = data.replace(/<style[^>]+?\/>|<style(.|\s)*?\/style>/gi, '')
return data;
}
/**
* jQuery.ajax mid - CROSS DOMAIN AJAX
* ---
* @author James Padolsey (http://james.padolsey.com)
* @version 0.11
* @updated 12-JAN-10
* ---
* Note: Read the README!
* ---
* @info http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
*/
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (data.results.length > 0) {
var res = filterData(data.results[0]);
if (_success) {
_success.call(this, {
responseText: res
}, 'success');
}
}
else {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: ""
}, 'success');
}
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment