使用异步轮询readyState的XMLHTTPRequest

XMLHTTPRequest used asynchronously polling the readyState

本文关键字:readyState XMLHTTPRequest 异步      更新时间:2023-10-16

下面是我的代码:

var
  xhttp: OleVariant;
xhttp := CreateOleObject('MSXML2.XMLHTTP');
xhttp.Open('GET', URL, True);
xhttp.send();
while xhttp.readyState <> 4 do
begin
  Application.HandleMessage;        
end;
// status property is available only when readyState is complete
if (xhttp.Status = 200) then... 
// do something

在这种情况下,我不想使用事件onreadystatechange

: readyState上轮询值为4的是否安全,在之后,我调用Send,或者是否有陷入无限循环的风险?


一些事实:

ServerXMLHTTPRequest可以在循环内使用waitForResponse,但我想使用XMLHTTPRequest组件。这里指出:

waitForResponse方法比轮询readyState属性,这是等待异步调用的唯一方法使用XMLHTTP组件发送

如果您担心无限循环,那么只需为循环实现超时,例如:

var 
  xhttp: OleVariant; 
  Ticks: DWORD;
  function TimeoutElapsed: Boolean;
  var
    Cur, Elapsed: DWORD;
  begin
    Cur := GetTickCount();
    if Cur >= Ticks then
      Elapsed := Cur - Ticks
    else
      Elapsed := (MAXDWORD - Ticks) + Cur;
    Result := (Elapsed >= 15000);
  end;
begin
  xhttp := CreateOleObject('MSXML2.XMLHTTP'); 
  xhttp.Open('GET', URL, True); 
  xhttp.send(); 
  Ticks := GetTickCount();
  while (xhttp.readyState <> 4) and (not TimeoutElapsed()) do
  begin
    if MsgWaitForMultipleObjects(0, nil, False, 1000, QS_ALLINPUT) = WAIT_OBJECT_0 then
      Application.ProcessMessages();         
    Ticks := GetTickCount();
  end; 
  // status property is available only when readyState is complete 
  if xhttp.readyState = 4 then
  begin
    if (xhttp.Status = 200) then...  
  end;
end;