0

Why does the following javascript code seem to run function handleResponse() without it being called? The following code uses the Google Books API.

<html>
  <head>
    <title>Google Books API Example</title>
  </head>
  <body>
    <div id="content"></div>
    <script>
      function handleResponse(response) {
        var item = response.items[0];
        document.getElementById("content").innerHTML = item.volumeInfo.title + "<br>" + item.volumeInfo.authors[0];
        
    }
    </script>
    <script src="https://www.googleapis.com/books/v1/volumes?q=rosie+project&callback=handleResponse"></script>
  </body>
</html>

1
  • Read about JSONP. handleResponse() is getting called by a script that the google API generates. Commented Feb 19, 2015 at 2:11

3 Answers 3

3

You passing the query string to the url: callback=handleResponse.

At the server a script is generate to invoke the callback function as a response.

enter image description here

Try updating the callback, like i did, callback=reply2me:

https://www.googleapis.com/books/v1/volumes?q=rosie+project&callback=reply2me

enter image description here

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

Comments

1

handleResponse() is a jsonp callback. This is primarily a form of communication in web pages which is a workaround to the browser's same-origin policy.

Many services use this form of communication, for e.g. twitter.

The pattern here is that you pass something in the url (usually a parameter called callback) which is actually the name of the method on your web page (in this case handleResponse). The service (which has data) will form javascript to the effect that handleResponse will get executed (as a normal js function with arguments). The arguments can be for e.g. some data returned by the service. In the case of twitter this may be timeline feeds; in your case your book search.

Essentially you are calling that url in a script tag...and javascript to the following effect is executed:

handleResponse(some_data);

Comments

0

The script you load with the URI

https://www.googleapis.com/books/v1/volumes?q=rosie+project&callback=handleResponse

calls handleResponse when it loads because you pass it as a query param.

Comments

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.