通过XMLHttpRequest加载外部图片文件或数据

来源:互联网 发布:资金盘系统源码 编辑:程序博客网 时间:2024/06/18 15:18

Chrome 团队已经封装好了一个库供开发者使用:Chrome Packaged Apps Resource Loader

var remoteImage,     container = document.querySelector('.imageContainer'),    toLoad = { 'images': [        'http://myserver.com/image1.png',        'http://myserver.com/image2.png' ] }; // list of image URLstoLoad.images.forEach(function(imageToLoad) {      remoteImage = new RAL.RemoteImage(imageToLoad);      container.appendChild(remoteImage.element);      RAL.Queue.add(remoteImage);});RAL.Queue.setMaxConnections(4);RAL.Queue.start();

如果只想简单的使用,没有这么多需求而去载入一个库,可以简单的封装一个函数来处理:

function loadImage(uri,callback){if(typeof callback!='function'){callback=function(uri){console.log(uri);}}var xhr = new XMLHttpRequest();xhr.responseType = 'blob';xhr.onload = function() {callback(window.URL.createObjectURL(xhr.response));}xhr.open('GET', uri, true);xhr.send();}//使用方法var imgUrl='http:xxx.jpg';loadImage(imgUrl,function(URI){//Do some thing while image is load});

function loadUrl(uri,callback){if(typeof callback!='function'){callback=function(uri){console.log(uri);}}var xhr = new XMLHttpRequest();xhr.responseType = 'text';xhr.onload = function() {callback(xhr.response);}xhr.open('GET', uri, true);xhr.send();}//使用方法var url = 'http:xxx.do';loadUrl(url,function(data){//Do some thing while image is load});

XMLHttpRequest.responseType:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType
如:"document","json","text","blob"