我正在尝试发送HTTP请求以为程序加载JSON文件。但是,它将连续加载最后的JSON文件而不会停止。我至少要加载6个JSON文件和1个JS文件,并且只有最后一个JSON文件加载达到5000+,并且仍然没有停止。加载所需文件后,如何阻止它发送HTTP请求?
起初,我认为它以递归方式调用错误回调,因此我尝试删除了错误函数调用。我还尝试创建一个变量来计算已加载文件的数量,以便在达到最大加载文件数时停止HTTP请求。
这是我的代码:
// Build the URL to query
attrs['url'] = url+(qs ? '?'+qs:'');
if(attrs['dataType']=="jsonp"){
var script = document.createElement('script');
script.src = attrs['url'];
document.body.appendChild(script);
return this;
}
// code for IE7+/Firefox/Chrome/Opera/Safari or for IE6/IE5
oReq = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
oReq.addEventListener("load", window[cb] || complete);
oReq.addEventListener("error", error);
oReq.addEventListener("progress", progress);
var responseTypeAware = 'responseType' in oReq;
if(attrs.beforeSend) oReq = attrs.beforeSend.call((attrs['this'] ? attrs['this'] : this), oReq, attrs);
function complete(evt) {
if(oReq.status === 200) {
attrs.header = oReq.getAllResponseHeaders();
var rsp = oReq.response || oReq.responseText;
if(attrs['dataType']=="json") try{rsp = JSON.parse(rsp.replace(/[\n\r]/g,"\\n").replace(/^([^\(]+)\((.*)\)([^\)]*)$/,function(e,a,b,c){ return (a==cb) ? b:''; }).replace(/\\n/g,"\n"))} catch(e){error(e);};
// Parse out content in the appropriate callback
if(attrs['dataType']=="script"){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.innerHTML = rsp;
document.head.appendChild(fileref);
}
attrs['statusText'] = 'success';
if(typeof attrs.success==="function") attrs.success.call((attrs['this'] ? attrs['this'] : this), rsp, attrs);
}else{
attrs['statusText'] = 'error';
error(evt)
}
if(typeof attrs.complete==="function") attrs.complete.call((attrs['this'] ? attrs['this'] : this), rsp, attrs);
//Debugging purposes
console.log(attrs['url']);
}
function error(evt){
if(typeof attrs.error==="function") attrs.error.call((attrs['this'] ? attrs['this'] : this),evt,attrs);
}
function progress(evt){
if(typeof attrs.progress==="function") attrs.progress.call((attrs['this'] ? attrs['this'] : this),evt,attrs);
}
if(responseTypeAware && attrs['dataType']){
try { oReq.responseType = attrs['dataType']; }
catch(err){error(evt); }
}
try{oReq.open('GET', attrs['url']);}
catch(err){error(evt); }
try{ oReq.send();}
catch(err){error(evt); }
return this;
}
stuQuery.prototype.loadJSON = function(url,fn,attrs){
if(!attrs) attrs = {};
attrs.dataType = "json";
attrs.complete = fn;
this.ajax(url,attrs);
return this;
}
另外一个注意事项:它成功加载了JSON文件,只是不会停止加载。