我需要对第一个XHR执行条件检查,如果满足条件,则执行第二个XHR,它将使用set request header来限制范围。
function getData( url )
{
if (y==0) {
alert ("you set vaue of y to 1");
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if ( request.readyState == 4 ){
renderData( request.responseText );
request.open( "GET", "TheData.csv", true );
//request.send( null );
y = 1;
}
}
} else {
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if ( request.readyState == 4 ){
renderData( request.responseText );
request.open( "GET", "TheData.csv", true );
//request.send( null );
request.setRequestHeader("Range", "bytes=" + BytesRead + "-");
}
}
}
}
答案 0 :(得分:0)
您目前的逻辑如下:
这意味着请求在响应返回之前不会被发送。从逻辑上讲,在发送请求之前响应不会返回(Javascript / internet不支持时间循环逻辑,抱歉)。这意味着请求永远不会被发送。也许你想要这个:
编辑代码,
function getData( url ){
if (y==0) {
alert ("you set vaue of y to 1");
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if ( request.readyState == 4 ){
renderData( request.responseText );
y = 1;
}
request.open( "GET", "TheData.csv", true );
request.send( null );
}
} else {
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if ( request.readyState == 4 ){
renderData( request.responseText );
request.setRequestHeader("Range", "bytes=" + BytesRead + "-");
}
}
request.open( "GET", "TheData.csv", true );
request.send( null );
}
}
还要注意你重复一下自己。您可以将代码缩短为
function getData( url ){
var request = new XMLHttpRequest();
if (y!=0) {
request.setRequestHeader("Range", "bytes=" + BytesRead + "-");
}
request.onreadystatechange = function(){
if ( request.readyState == 4 ){
renderData( request.responseText );
y = 1; //assuming `y` never gets reset to 0
}
}
request.open( "GET", "TheData.csv", true );
request.send( null );
}
还要注意变量BytesRead
应该是小写的,而不是大写的(=> bytesRead
),并且您不需要传递null
参数来发送(如果我正确阅读文档。
另请注意,通过全局变量传递参数是一种不好的做法。在你的情况下,BytesRead
看起来像一个全局变量(我不认为这是一个内部函数)。
另请注意,如果您愿意使用jQuery,jQuery会简化过程,即使您使用自定义标头:
function getData(url){
var headers = {};
if(y!=0){
headers.range = "bytes=" + BytesRead + "-"
}
$.ajax(url, {
headers: headers,
dataType: "text" //prevent automatic parsing (degression)
}).done(function(response){
renderData(response);
y=1;
});
}
甚至
function getData(url){
$.ajax(url, {
headers: (y!=0) ? {} : {range : "bytes=" + BytesRead + "-"},
dataType: "text"
}).done(function(response){
renderData(response);
y=1;
});
}
参考:https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest