Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing getJSON to JSONP

I have this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $.getJSON('http://example.com/api/get_cats', function(fbResults) {
            document.write(fbResults.cats[0].title);
        });
    });
</script>

How can I change this code:

<script>
    $(document).ready(function() {
        $.getJSON('http://example.com/api/get_cats', function(fbResults) {
            document.write(fbResults.cats[0].title);
        });
    });
</script>

for it to work as JSONP ... Is this totally different?

like image 269
Satch3000 Avatar asked Aug 11 '12 18:08

Satch3000


People also ask

Why is JSONP avoided?

JSONP is not actually JSON with padding, it's Javascript code that's executed. JSON is not a real subset of Javascript and the way it is not is important to us: via UTFGrid, we are all UTF-8 masters. JSONP is not safe: it's Javascript that's executed. It's trivial to XSS with JSONP, because JSONP is XSS.

Is JSONP deprecated?

Yes, JSONP is obsolete now. There's absolutely no reason to offer a JSONP service anymore.

How do I create JSONP?

It's idea is to simply return a JavaScript file which calls the callback function with the JSON object as the first parameter of the JavaScript callback function. You can use the built-in json_encode() function to create JSON strings (which $data in our example above contains) from arrays and objects in PHP.

How do I get JSONP data?

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.


1 Answers

Actually, you just have to add ?callback=?, jQuery does the rest.

$(document).ready(function() {
    $.getJSON('http://example.com/api/get_cats?callback=?', function(fbResults) {
        document.write(fbResults.cats[0].title);
    });
});
like image 94
Jill-Jênn Vie Avatar answered Oct 05 '22 00:10

Jill-Jênn Vie