Search code examples
javascriptjsonp

Making and handling JSONP request using JavaScript


I would like to make cross domain request in the client end, so I chose JSONP. I am new to JSONP and would like to make a request to http://somedomain.com using JavaScript and not jQuery. It would be very helpful for my development if I get sample snippet to make and handle a request using JSONP in JavaScript.


Solution

  • Here's a small example fetching data from a google spreadsheet:

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
       "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    <head>
        <title>jsonp</title>
    </head>
    <body>
        <span></span>
        <script>
            //this function is the callback, it needs to be a global variable
            function readResponse(response){
                document.getElementsByTagName('SPAN')[0].innerHTML = response.feed.entry.length + ' entries returned';
                console.log(response);
            }
            (function(){
                //note the "readResponse" at the end
                var src = 'http://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json-in-script&callback=readResponse',
                    script = document.createElement('SCRIPT');
                script.src = src;
                document.body.appendChild(script);
            })();
    
        </script>
    </body>
    </html>
    

    One comment related to this example. If you want to play with your own google spreadsheet, you need to both share it as public, and publish it.