Tuesday, July 30, 2013

Pulling cross origin data within JavaScript

It took me a lot longer to figure this out than I thought it would, and the syntax has to be just so, minor changes cause failure due to same origin policy.

Using JQuery this code will allow you to pull data from an external website.
$.ajax({
    url: 'http://domain.com/data-request.php?foo=bar',
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    timeout: 5000,
    success: function(data, status){
        //data loaded
    },
    error: function(){
        //error loading data
    }
});
Data must be formatted in JSON format. I can't remember the site I found this on, but it gives a lot of detail on what's happening and why.

No comments:

Post a Comment