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?

3
  • Is the data offered from the server as JSONP? Commented Aug 11, 2012 at 19:07
  • There's just JSON data on the server Commented Aug 11, 2012 at 19:17
  • 3
    Then it won't work as a JSONP request. JSONP is basically just a <script> request. The response must have the data wrapped in a function call, like my_func({"foo":"bar"}). Then when the script arrives, assuming there's a function named my_func, that function is invoked passing the data into it. Some servers let you specify the function name, and they'll return the JSONP response, but this behavior must be established on the server. Commented Aug 11, 2012 at 19:25

1 Answer 1

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);
    });
});
Sign up to request clarification or add additional context in comments.

2 Comments

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 I added output=jsonp&callback=? as parameters in order to get rid off this error

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.