Created
February 10, 2012 22:54
-
-
Save rogerbraun/1793752 to your computer and use it in GitHub Desktop.
JSONP
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); | |
} | |
button.onclick = function() { | |
query = input.value; | |
url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" + query; | |
doJsonP(url, function(json) { | |
var results = json.responseData.results; | |
results.forEach(function(result) { | |
var img = document.createElement("img"); | |
img.src = result.url; | |
images.appendChild(img); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment