7

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.

1

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great example! Here's another one.. it's a JSBin that can be used to fiddle with JSONP from Wikipedia. It was referenced in this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.