I am currently working on a project that required me to make a cross-domain AJAX request using jQuery. This is a function that is disabled by default because of security implications, however, there is occasionally a need for this type of request. In this case, I need to load content from a remote URL or website similar to how you would load content using jQuery’s .load() function or using PHP’s file_get_contents() function.
/******************************************************************************** FUNCTION FOR CROSS DOMAIN AJAX REQUEST USING JQUERY 1.5+ ********************************************************************************/ function loadContents(url, callback) { //CONFIRM A URL WAS PROVIDED if(url) { //SET URL FOR YAHOO YQL QUERY var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + url + '"') + '&format=xml&callback=?'; //MAKE YAHOO YQL QUERY $.getJSON(yql,function(data) { //BUILD CALLBACK FUNCTION if(typeof callback === 'function') { callback(data.results[0]); } //WRITES ERROR TO LOG }).error(function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); } ); //LOG ERROR IF NO URL WAS PASSED TO THE SCRIPT } else { console.log('No site was passed to the script.'); } } /******************************************************************************** SAMPLE USAGE ********************************************************************************/ loadContents('http://www.ziplineinteractive.com/frame/', function(results) { $('#wrapper').html(results); }); |
I have tested this function in IE, Firefox, Chrome, and Safari and it should allow you to make cross-domain AJAX requests in jQuery 1.3, 1.4, 1.5, 1.6, 1.7, and from what I been able to find online it should also be supported in 1.8, although, 1.8 is not available at this time.
Let me know how this works in your application.
You can change the format to json (i.e. format=json) for a more JavaScript-y response.
This worked great, thanks for sharing!
@Casey Glad to hear it worked well for you.
thank you MAN!