Created
February 11, 2012 17:37
-
-
Save rogerbraun/1802929 to your computer and use it in GitHub Desktop.
JSONP example 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>JSON-P Example</title> | |
<script src="jsonp.js"></script> | |
</head> | |
<body> | |
<h1>A simple JSON-P example</h1> | |
<p>This is a Google Image Search.</p> | |
<input id="q" /> | |
<button id="search">Search</button> | |
<div id="images" /> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.onload = function(){ | |
var button = document.getElementById("search"); | |
var input = document.getElementById("q"); | |
var body = document.body; | |
var images = document.getElementById("images"); | |
var doJsonP = function(url, callback) { | |
jsonpcallback = callback; | |
request_url = url + "&callback=jsonpcallback"; | |
var request = document.createElement("script"); | |
request.src = request_url; | |
body.appendChild(request); | |
} | |
var addPictures = function(start, max, url) { | |
if(start >= max){ return null}; | |
var request_url = url + "&start=" + start; | |
doJsonP(request_url, function(json) { | |
var results = json.responseData.results; | |
results.forEach(function(result) { | |
var img = document.createElement("img"); | |
img.src = result.url; | |
images.appendChild(img); | |
}); | |
}); | |
addPictures(start + 8, max, url); | |
} | |
button.onclick = function() { | |
query = input.value; | |
url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&safe=off&q=" + query; | |
addPictures(0, 20, url); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment