Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 342
Balaji Avatar asked May 06 '11 06:05

Balaji


People also ask

How do I create a JSONP request?

Method to use JSONP: In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.

Can JSONP execute JavaScript?

JSONP enables sharing of data bypassing same-origin policy, which disallows running JavaScript code to read media DOM elements or XMLHttpRequest data fetched from outside the page's originating site.

What does JSONP use for request?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

What is difference between JSON and JSONP?

Json is stardard format that is human readable used to transmit information from one server to another server. Jsonp is a json with ability to transmit information to another domain. JSONP is JSON with padding, that is, you put a string at the beginning and a pair of parenthesis around it.


1 Answers

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.

like image 186
Mic Avatar answered Oct 13 '22 20:10

Mic