Fork me on GitHub

JSONProxy

Travis CI build status

Enables cross-domain requests to any JSON API.

Very useful for mashup sites - since API calls can be done client-side, no server code is needed. Note that exposing API secret keys in client code is discouraged. Examples in jQuery, though it is not required.

Easy: JSONP

<script>
  function myCallback(data){
    alert('it works! ', JSON.parse(data).awesome);
  }
</script>
<script src="https://jsonp.nodejitsu.com/?callback=myCallback&url=http://jsonview.com/example.json"></script>

<!-- or the jQuery convenience method -->

<script>
  $.getJSON('https://jsonp.nodejitsu.com/?callback=?&url=http://jsonview.com/example.json', function(data){
    alert('fake AJAX! ' + data.awesome);
  });
</script>
http://jsonp.jit.su/?callback=&url=

Easier: Cross-domain AJAX (CORS)

(not supported by IE < 10)

<script>
  $.get('https://jsonp.nodejitsu.com/?url=http://jsonview.com/example.json', function(data){
    alert('pretty awesome, eh? ' + data.awesome);
  });
</script>
http://jsonp.jit.su/?url=

Easiest: jQuery Plugin

Wrapper function of jQuery.ajax(), which detects browser support and picks the best available transport:

  1. CORS directly
  2. CORS via proxy
  3. JSONP directly
  4. JSONP via proxy

In addition to the options available for jQuery.ajax(), the plugin adds two additional options: corsSupport and jsonpSupport.

<script src="jquery.js"></script>
<script src="uri.js"></script>
<script src="jsonp.js"></script>
<script>
  $.jsonp({
    url: 'http://jsonview.com/example.json', // any JSON endpoint
    corsSupport: true, // if URL above supports CORS (optional)
    jsonpSupport: true, // if URL above supports JSONP (optional)

    success: function(data){
      alert('CORS or JSONP! ' + data.awesome);
    }
    // error, etc.
  });
</script>

Installation

bower install jsonproxy, or download directly. Requires jQuery 1.5+ and URI.js.


CORS vs. JSONP

Unfortunately, detection of response errors with JSONP is difficult, at best. jQuery's JSONP implementation won't call an error callback unless an explicit timeout is specified (which the plugin takes care of) - see here for more info and options.

CORS, however, is just normal AJAX! There is also a security advantage, in that it's not possible for a malicious service (including this one) to run arbirtrary JavaScript on your page.