Reputation: 305
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>
Upvotes: 0
Views: 445
Reputation: 11975
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);
Upvotes: 1
Reputation:
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.
Try updating the callback, like i did, callback=reply2me
:
https://www.googleapis.com/books/v1/volumes?q=rosie+project&callback=reply2me
Upvotes: 3
Reputation: 13560
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.
Upvotes: 0