Modify HTTP Headers for a JSONP request

JSON with Padding works by adding a script element to the page, with the src attribute pointing to the URL of the web service. The web service then returns a script containing the data wrapped in a callback function that is executed when the script finishes parsing. It’s not so much JSON (it doesn’t even have to be valid JSON, for a start) as it is Plain JavaScript.

There’s no way to modify the headers sent for a script element that’s added to your page, unfortunately. The only thing you can do is check for a cross-origin compatible method of retrieving data, such as:

  • XMLHttpRequest Level 2 – Chrome, Safari 4+, Firefox 3.5+, Opera

    // Is XMLHttpRequest Level 2 supported?
    if ("withCredentials" in new XMLHttpRequest()) 
  • XDomainRequest – for IE 8, IE 9

    // Is XDomainRequest supported?
    if ("XDomainRequest" in window)

It would be a good idea to test for these implementations if they exist and use them accordingly, falling back to standard JSONP for unsupported or older browsers.

It’s also possible (but unlikely, given that it’s high profile) that the web service isn’t set up to allow cross-origin requests, so you may still have to fall back to JSONP if the request fails. See also, Cross-Origin Resource Sharing.

Leave a Comment