Класс Sys.Net.XMLHttpExecutor

Выполняет асинхронный сетевой запрос используя поддержку XMLHTTP веб-обозревателем.

Пространство имен: Sys.Net

Наследования: отсутствуют

var executor = new Sys.Net.XMLHttpExecutor();

Члены

Имя

Описание

Конструктор Sys.Net.XMLHttpExecutor

Инициализирует новый экземпляр класса Sys.Net.XMLHttpExecutorпри реализации в производном классе.

Метод Sys.Net.XmlHttpExecutor abort

Останавливает незавершенный сетевой запрос, сделанный исполнителем.

Метод Sys.Net.XmlHttpExecutor executeRequest

Выполняет сетевой запрос, как указано в соответствующем экземпляре объекта WebRequest.

Метод Sys.Net.XmlHttpExecutor.getAllResponseHeaders

Возвращает все заголовки откликов.

Метод Sys.Net.WebRequestExecutor.getResponseHeader

Метод Sys.Net.XmlHttpExecutor.getResponseHeader

Возвращает значение заданного заголовка отклика.

Свойство Sys.Net.XmlHttpExecutor aborted

Возвращает значение, которое указывает, была ли преждевременно завершена работа исполнителя.

Свойство Sys.Net.XmlHttpExecutor responseAvailable

Возвращает значение, которое указывает, вернулся ли сетевой запрос без преждевременного завершения и превышения времени ожидания.

Свойство Sys.Net.XmlHttpExecutor responseData

Возвращает текстовое представление тела ответа.

Свойство Sys.Net.XmlHttpExecutor started

Возвращает значение, указывающее, выполнено ли исполнителем перенаправление запроса к объекту XMLHTTP обозревателя.

Свойство Sys.Net.XmlHttpExecutor statusCode

Возвращает код состояния объекта XMLHTTP обозревателя.

Свойство Sys.Net.XmlHttpExecutor statusText

Возвращает текст состояния от объекта XMLHTTP обозревателя.

Свойство Sys.Net.XmlHttpExecutor timedOut

Возвращает значение, указывающее, было ли превышено время ожидания исполнителя.

Свойство Sys.Net.XmlHttpExecutor xml

Возвращает объект XMLDOM , который содержит XML-ответ от объекта XMLHTTP обозревателя.

Заметки

Класс XmlHttpExecutor функционирует как исполнитель, заданный по умолчанию, и является реализацией абстрактного класса WebRequestExecutor.

Так как исполнитель по умолчанию уже задан, то нет необходимости создавать экземпляр класса и связывать его с веб-запросом. Однако если задан настраиваемый исполнитель, необходимо создать экземпляр исполнителя и выбрать его в качестве исполнителя по умолчанию для данного веб-запроса.

После завершения сетевого вызова объект XmlHttpExecutor следует использовать только для получения данных ответа, после чего его удалить.

Примечание

Дополнительные сведения об объекте XMLHTTP см. в разделе О собственном XMLHTTP.

Пример

В следующем примере демонстрируется использование методов и свойств класса XmlHttpExecutor. В примере показаны веб-страница и клиентский скрипт, используемый для взаимодействия с классом XmlHttpExecutor.

var resultElementId;

function pageLoad()
{
    resultElementId = $get("ResultId");
}

// This function aborts a Web request.
function AbortWebRequest()
{
    // Create the WebRequest object.
    wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url("getTarget.htm");

   // Clear the results area.
    resultElementId.innerHTML = "";

    // Set the Completed event handler, 
    // for processing return data
    wRequest.add_completed(OnCompleted);

    // Make the request.
    wRequest.invoke();

    // Get the current executor.
    var executor = wRequest.get_executor();


    // Abort the request.
    executor.abort();

    // Check if the executor is aborted.
    var execAborted = 
        executor.get_aborted();

    alert("Executor aborted: " + execAborted);
}

// This function executes a Web request.
function ExecuteWebRequest()
{
    // Create the WebRequest object.
    wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url("getTarget.htm");


    // Set the Completed event handler, for processing return data
    wRequest.add_completed(OnCompleted);

      // Clear the results area.
    resultElementId.innerHTML = "";

    // To use executeRequest you must instantiate the
    // executor, assign it to the Web request instance,
    // then call the executeRequest function.
    // Note: Normally to make a Web request you use
    // the invoke method of the WebRequest instance.
    var executor = new Sys.Net.XMLHttpExecutor();
    wRequest.set_executor(executor); 
    executor.executeRequest();

    var started = executor.get_started();

    alert("Executor started: " + started);
}



// This is the event handler called after 
// the Web request returns.
function OnCompleted(executor, eventArgs) 
{
    if(executor.get_responseAvailable()) 
    {

        // Get the Web request instance.
        var webReq = executor.get_webRequest();
        // Display request Url.
        alert(webReq.get_url());

       // Clear the previous results. 
       resultElementId.innerHTML = "";

       // Display the Web request status. 
       resultElementId.innerHTML +=
          "Request Status: [" + executor.get_statusCode() + " " + 
                    executor.get_statusText() + "]" + "<br/>";

        // Display the Web request headers.
        resultElementId.innerHTML += "Headers: <br/>";


        // Get all the headers.    
        resultElementId.innerHTML += 
        "All Request Headers: " +
            executor.getAllResponseHeaders() + "<br/>"; 

        // Get a specific header.
        resultElementId.innerHTML += 
        "Content-Type Header: " +
            executor.getResponseHeader("Content-Type") + 
            "<br/>";       

        // Display Web request body.
        resultElementId.innerHTML += "Body: <br/>";
        resultElementId.innerText += 
            executor.get_responseData();


    }
    else
    {
        if (executor.get_timedOut())
            alert("Timed Out");
        else
            if (executor.get_aborted())
                alert("Aborted");
    }

}

// This is the event handler called after 
// the Web request returns. It is designed
// for Web requests that return XML.
function OnSucceededXml(executor, eventArgs) 
{
    if (executor.get_responseAvailable()) 
    {
        // Display XML.
       if (document.all)
            resultElementId.innerText += executor.get_xml().xml;
        else
            // Firefox 
            resultElementId.textContent += "First node: " + 
                executor.get_xml().documentElement.nodeName;

    }
    else
    {
        if (executor.get_timedOut())
            alert("Timed Out");
        else
            if (executor.get_aborted())
                alert("Aborted");
    }
} 

// This function executes a Web request
// to get XML data.
function GetXml()
{
    // Create the WebRequest object.
    wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url("getTarget.xml");

     // Set the Completed event handler 
    // for processing return data.
    wRequest.add_completed(OnSucceededXml);

    // Clear the results area.
    resultElementId.innerText = "";

    // Invoke the Web request.
    wRequest.invoke();
}


// This function aborts a Web request.
function AbortWebRequest()
{
    // Create the WebRequest object.
    wRequest =  new Sys.Net.WebRequest();

    // Set the request Url.  
    wRequest.set_url("getTarget.htm");

   // Clear the results area.
    resultElementId.innerHTML = "";

    // Set the Completed event handler, 
    // for processing return data
    wRequest.add_completed(OnCompleted);

    // Make the request.
    wRequest.invoke();

    // Get the current executor.
    var executor = wRequest.get_executor();


    // Abort the request.
    executor.abort();

    // Check if the executor is aborted.
    var execAborted = 
        executor.get_aborted();

    alert("Executor aborted: " + execAborted);
}

См. также

Ссылки

Класс Sys.Net.WebRequestExecutor

Класс Sys.Net.WebRequestManager

Класс Sys.Net.WebRequest