Last active
December 13, 2015 21:08
-
-
Save georgeOsdDev/4975013 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
<html> | |
<head> | |
<meta charset="utf-8"> | |
<meta name=description content="JSONP SAMPLE"> | |
<meta name=viewport content="width=device-width, initial-scale=1"> | |
<title>JSONP</title> | |
</head> | |
<body> | |
<h2>JSONP Sample</h2> | |
<script src="./jsonp_client.js" type="text/javascript" charset="utf-8"></script> | |
<script type="text/javascript"> | |
var jsonp = new JSONP(); | |
jsonp.request("https://api.github.com",function(data){ | |
console.log(data); | |
}); | |
jsonp.request("https://api.github.com/legacy/repos/search/:javascript",function(data){ | |
console.log(data); | |
}); | |
</script> | |
</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
(function(global){ | |
global.jsonpCallbacks = { | |
index:0 | |
}; | |
function JSONP(){ | |
this.s ={}; | |
} | |
JSONP.prototype.request = function(url,cb){ | |
var key = "_"+global.jsonpCallbacks.index++, | |
sep = "?", | |
self = this; | |
this.s[key] = document.createElement('script'); | |
if (url.indexOf("?") > 0){ | |
sep = "&"; | |
} | |
this.s[key].src = url + sep + "callback=" + 'jsonpCallback'+key; | |
this.s[key].type ="text/javascript"; | |
global["jsonpCallback"+key] = function(json){ | |
self.s[key].parentNode.removeChild(self.s[key]); | |
delete global["jsonpCallback"+key]; | |
cb(json); | |
}; | |
document.getElementsByTagName('head')[0].appendChild(this.s[key]); | |
}; | |
global.JSONP = JSONP; | |
})(this); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment