JavaScript (index.html):
<div id="output_getjsonp"></div> <script type="text/javascript"> var getjsonp = function() { this.head = document.getElementsByTagName('head')[0] || document.documentElement; this.current = null; this.queue = []; }; getjsonp.prototype.request = function(q) { var fid = (q.fid||'_getjsonp') + new Date().getTime(); console.log(fid); var script = document.createElement('script'); script.src = q.url.replace('callback=?', 'callback=' + fid); this.queue.push({ fid : fid, script : script, load : q.load }); if(!this.current) this.action(); }; getjsonp.prototype.action = function() { var self = this; this.current = null; if(this.queue.length) { this.current = this.queue.shift(); window[this.current.fid] = function(data) { self.head.removeChild(self.current.script); self.current.load && self.current.load(data); self.action(); }; this.head.appendChild(this.current.script); } }; var jsonp = new getjsonp(); jsonp.request({ fid : '_myjsonp', url : 'http://codeboxy.blogspot.com/feeds/posts/default?alt=json&callback=?', load : function(data) { document.getElementById('output_getjsonp').innerHTML = data.feed.entry[0].title.$t; } }); </script>
範例結果:
說明:
動態使用jsonp取得json資料,測試支援版本:
- Google Chrome 33.0.1750.146 m
- Firefox 27.0.1
- IE 11.0.9600.16518
沒有留言:
張貼留言