7

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?

rrk
  • 15,677
  • 4
  • 29
  • 45
Satch3000
  • 47,356
  • 86
  • 216
  • 346
  • Is the data offered from the server as JSONP? –  Aug 11 '12 at 19:07
  • There's just JSON data on the server – Satch3000 Aug 11 '12 at 19:17
  • 3
    Then it won't work as a JSONP request. JSONP is basically just a ` –  Aug 11 '12 at 19:25

1 Answers1

35

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);
    });
});
rrk
  • 15,677
  • 4
  • 29
  • 45
Jill-Jênn Vie
  • 1,849
  • 19
  • 22
  • 8
    I get "Uncaught SyntaxError: Unexpected token :" because my php is returning json. How do format the php side to call the callback function when it doesn't have a name? – Curtis Jul 14 '14 at 18:29
  • 2
    @curtis I added `output=jsonp&callback=?` as parameters in order to get rid off this error – AlexB Dec 21 '16 at 08:42