Класс Sys.Net.XMLHttpExecutor
Выполняет асинхронный сетевой запрос используя поддержку XMLHTTP веб-обозревателем.
Пространство имен: Sys.Net
Наследования: отсутствуют
var executor = new Sys.Net.XMLHttpExecutor();
Члены
Имя |
Описание |
---|---|
Инициализирует новый экземпляр класса Sys.Net.XMLHttpExecutorпри реализации в производном классе. |
|
Останавливает незавершенный сетевой запрос, сделанный исполнителем. |
|
Выполняет сетевой запрос, как указано в соответствующем экземпляре объекта WebRequest. |
|
Возвращает все заголовки откликов. |
|
Возвращает значение заданного заголовка отклика. |
|
Возвращает значение, которое указывает, была ли преждевременно завершена работа исполнителя. |
|
Возвращает значение, которое указывает, вернулся ли сетевой запрос без преждевременного завершения и превышения времени ожидания. |
|
Возвращает текстовое представление тела ответа. |
|
Возвращает значение, указывающее, выполнено ли исполнителем перенаправление запроса к объекту XMLHTTP обозревателя. |
|
Возвращает код состояния объекта XMLHTTP обозревателя. |
|
Возвращает текст состояния от объекта XMLHTTP обозревателя. |
|
Возвращает значение, указывающее, было ли превышено время ожидания исполнителя. |
|
Возвращает объект 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