/*Wrap ajax requests in a promise.Usage: xhr(form).then(success).catch(error);It's also possible to call: var request = xhr(form).then(success).catch(error); request.cancel();Which aborts the request (and rejects the promise).You may also call xhr(a[href]).then(success).catch(error);TODO: Look more at the cancel/abort stuff: should we reject in a more custom way?*/import{serialise}from'./form';exportfunctionxhr(form){varrequest=newXMLHttpRequest();varpromise=newPromise(function(resolve,reject){varmethod=form.method||'get',action,data,enctype;if(form.action!==undefined){// We check here to see if we are doing a GET request, as// that requires us to open a different url, including the// query string. It's rather annoying that we can't get this// from a FormData() object, actually.if(method==='get'){action=form.action+'?'+serialise(form);}else{action=form.action;data=newFormData(form);enctype=form.enctype||'application/x-www-form-encoded; charset=UTF-8';}}elseif(form.href){action=form.href;}request.open(method,action);if(enctype){request.setRequestHeader('Content-Encoding',enctype);}request.setRequestHeader('X-Requested-With','XMLHttpRequest');request.onload=function(){if(request.status<400){resolve(newResponse(request));}else{reject(newResponse(request));}};request.onerror=function(){reject(newError("Network Error"));};request.send(data);});promise.cancel=request.abort.bind(request);returnpromise;}functionsplitHeaders(string){returnstring.split('\n').filter(Boolean).map(function(header){returnheader.replace(/: /,'\n').split('\n');});}classResponse{constructor(request){this.statusCode=request.status;this.content=request.response;this.headers=splitHeaders(request.getAllResponseHeaders());this._request=request;}getHeader(header){for(lethdrofthis.headers){if(hdr[0].toLowerCase()==header.toLowerCase()){returnhdr[1];}}}}
Comments (0)
HTTPSSSH
You can clone a snippet to your computer for local editing.
Learn more.