Кафедра: АСОИиУ
Лабораторная Работа
На тему: XMLHttpRequest (AJAX)
XMLHttpRequest (AJAX) - отправка и обработка ответов http-запросов с помощью JavaScript
Методы объекта XMLHttpRequest
Все нижеизложанные методы и свойства - общие для Internet Explorer 5, Mozilla, Netscape 7, и соответственно, использовать их можно безопасно.
abort()
обрывает текущий запрос
getAllResponseHeaders()
возвращает полный набор заголовков ответа (названий и значений) в виде строки
getResponseHeader(<headerLabel>)
возвращает строковое значение заголовка, название которого указано в параметре.
open(<method>, <URL> [, <asyncFlag> [, <userName> [, <password>]]])
Присвоение параметров (метода, URL, и других) текущему запросу.
send(<content>)
Посылает запрос
setRequestHeader(<label>, <value>)
Установка в отправляемом запросе заголовка <label> со значением <value>
Свойства объекта XMLHttpRequest
onreadystatechange
событие, возникающее при смене статуса объекта
readyState
значения статуса (integer), может принимать следующие значения: 0 = неинициализирован (uninitialized); 1 = "идет загрузка" (loading); 2 = "загружен" (loaded); 3 = "интерактивен" (interactive) 4 = "выполнен" (complete)
responseText
строка с возвращенными сервером данными
responseXML
DOM-совместимый объект-документ с возвращенными сервером данными
status
стандартный HTTP код статуса, например 404 (для "Not Found") или 200 (для "OK")
statusText
текстовое сообщение статуса
Здесь все необходимые свойства и методы этого объекта, которые помогут нам решить наш таск. Опишем последовательность наших действий:
Алгоритм:
1. Создание экземпляра объекта XMLHttpRequest.
2. Объявление обработчика события onreadystatechange нашего экземпляра.
3. Открытие соединения с указанием типа запроса, URL и других параметров.
4. Посыл запроса.
Алгоритм незамысловат, но, учитывая кое-какие нюансы (и учитывая, что мы учимся:)), конечно же, рассмотрим его подробней:
Итак, пункт первый - создание экземпляра объекта. Вот здесь всплывает особенность обеспечения кроссбраузерности. Конструкция создания объекта различна: в IE 5+ она реализована через ActiveXObject, а в остальных браузерах (Mozilla, Netscape и Safari) - как встроенный объект типа XMLHttpRequest.
Для InternetExplorer:
var request = new ActiveXObject("Microsoft. XMLHTTP");
Для всех остальных:
varrequest = newXMLHttpRequest();
Таким образом, чтобы обеспечить кроссбраузерность, нужно лишь проверять наличие объектов window. XMLHttpRequest и window. ActiveXObject и применять соответствующий вызов создания экземпляра.
Далее по плану - создание обработчика событий и открытие соединения. Это весьма просто:
request. onreadystatechange = processRequestChange;
request. open("GET", url, false);
Здесь мы используем метод GET, хотя можно и POST; в общем виде это выглядет так: request. open(<"GET"|"POST"|... >, <url>, <asyncFlag>);. Функцию, являющуюся обработчиком события onreadystatechange (в нашем случае это функция - processRequestChange()), мы должны определить сами.
Ну и последний пункт - посыл запроса - метод send() (для версии без ActiveX в качестве параметра нужно передать null).
// для IE
request. send();
// для остальных
request. send(null);
После запуска метода send() начинает работать вышеуказанный обработчик события onreadystatechange. Собственно, этот обработчик - основная часть программы. В нем обычно перехватываются все возможные коды состояния запроса и вызываются соответствующие действия, а также перехватываются возможные ошибки.
Исходя из всего вышесказанного, JavaScript код будет примерно следущим:
var request;
/**
* Load XMLDoc function
* Здесь в качестве параметра url при вызове мы должны указать
* backend-скрипт, который, собственно, и получит данные с сервера
*/
function doLoad(url) {
if (window. XMLHttpRequest) {
request = new XMLHttpRequest();
request. onreadystatechange = processRequestChange;
request. open("GET", url, true);
request. send(null);
} else if (window. ActiveXObject) {
request = new ActiveXObject("Microsoft. XMLHTTP");
if (request) {
request. onreadystatechange = processRequestChange;
request. open("GET", url, true);
request. send();
}
}
}
/**
* Get request state text function
*/
function getRequestStateText(code) {
switch (code) {
case 0: return "Uninitialized. "; break;
case 1: return "Loading... "; break;
case 2: return "Loaded. "; break;
case 3: return "Interactive... "; break;
case 4: return "Complete. "; break;
}
}
/**
* Event on request change
* Собственно, обработчик события onreadystatechange.
* Здесь мы, в зависимости от состояния запроса,
* будем скрывать / показывать слои "Загрузка данных",
* само поле данных и т.д.
*/
function processRequestChange() {
document. getElementById("resultdiv"). style. display = 'none';
document. getElementById("state"). value = getRequestStateText(request. readyState);
abortRequest = window. setTimeout("request. abort(); ", 10000);
// если выполнен
if (request. readyState == 4) {
clearTimeout(abortRequest);
document. getElementById("statuscode"). value = request. status;
document. getElementById("statustext"). value = request. statusText;
// если успешно
if (request. status == 200) {
document. getElementById("resultdiv"). style. display = 'block';
document. getElementById("responseHTML"). innerHTML = request. responseText;
} else {
alert("Не удалось получить данные: n" + request. statusText);
}
document. getElementById("loading"). style. display = 'none';
}
// иначе, если идет загрузка или в процессе - показываем слой "Загружаются данные"
else if (request. readyState == 3 || request. readyState == 1) {
document. getElementById("loading"). style. display = 'block';
}
}
Теперь HTML-формы нашего примера:
<input type="text"
id="search"
value="Введите первые буквы ника"
onFocus="this. value=''; document. getElementById('resultdiv'). style. display='none'; "
/>
<input type="button"
value="Поиск"
onClick="doLoad('ajaxsearch. php? search='+document. getElementById('search'). value);"
/><br /><br />
Дополнительная информация о выполнении запроса: <br /><br />
<table>
<tr>
<td>Состояние запроса: </td>
<td><input type="text" id="state" disabled="true" /></td>
</tr>
<tr>
<td>Код статуса: </td>
<td>
<input type="text" id="statuscode" disabled="true" />
<input type="text" id="statustext" disabled="true" />
</td>
</tr>
</table>
Обратите внимание на фрагмент, выделенный зеленным цветом - событие onClick кнопки "Поиск". Мы вызываем функцию doLoad(. .), в качестве параметра которой передаем адрес backend-скрипта, выполняющего поиск в базе зарегистрированного пользователя. О backend-скрипе чуть позже, имя его мы определили как ajaxsearch. php. Также GET-параметром скрипту мы передаем переменную search, со значением, взятым из поля ввода для ника.
И, как было сказано выше, объявим дополнительные HTML-элементы (в нашем случае - это невидимые слои) для отображения полученного содержимого и окна загрузки с возможностью отмены:
<div id="resultdiv" style="display: none; ">
Резульаты поиска:
<span id="responseHTML"></span>
</div>
<div id="loading"
style="
position: absolute;
top: 450px;
left: 550px;
display: none;
width: 125px;
height: 40px;
font-family: Verdana;
font-size: 11pt;
border: 1px solid #BBBBBB;
background: #EEEEEE;
padding: 5px 5px 5px 5px;
"
>
Loading data...
<div id="canselloading"
style="
background: red;
border: 1px solid #000000;
color: #FFFFFF;
padding: 2px 2px 2px 2px;
cursor: pointer;
"
onClick="
request. abort();
document. getElementById('loading'). style. display = 'none';
return false;
"
>Cansel
</div>
</div>
Ну что ж, с frontend'ом разобрались, переходим к backend'у - скрипт ajaxsearch. php. И вновь мы сталкиваемся с небольшими нюансами: для того, чтобы PHP-скрипт корректно работал с XMLHttpRequest, он (скрипт) должен посылать ряд заголовков. А именно: тип содержимого и его кодировку (особенно важно, если вы работаете с кириллицей), а также параметры кеширования - любое кеширование должно быть отключено (ну это и понятно - необходимо иметь свежую информацию).
Послать эти заголовки можно, примерно, так:
header("Content-type: text/html; charset=windows-1251");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
И еще одна особенность: если вы будете выводит данные в формате text/plane (в нашем случае - text/html, поэтому нас это не каснется, но все же - чтобы знать), помните, что спецсимволы такие как n, t, r и т.д., обрабатываются по умолчанию только в строках с двойными кавычками:
// т.е. правильно так
print"MessagenFromAJAX";
// а не так!
print 'MessagenFromAJAX';
Ну и теперь весьма банальный PHP-скрипт получения данных из базы (а банальный, потому что предполагается, что у вас уже есть навыки работы с базами данных в PHP). Вид скрипта следующий (в найденых никах мы подсвечиваем буквы запроса красным цветом и выводим все это в виде таблицы):
<? php
/**
* Посыл заголовков
*/
header("Content-type: text/plain; charset=windows-1251");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
/**
* Хост, логин и пароль базы данных
* (вам, естественно, нужно заменить на свои значения)
*/
$dbhost = "localhost";
$dblogin = "root";
$dbpassword = "root";
/**
* Коннектимся к базе, выполняем
* запрос, получаем результат
*/
@mysql_connect($dbhost, $dblogin, $dbpassword) or die("Unable to connect to database. ");
@mysql_select_db("MYDATABASE") or die("Unable to select database");
$sql = "SELECT * FROM users WHERE nick LIKE '%". $_GET ["search"]. "%' ORDER BY nick";
$result = mysql_query($sql);
print "Найдено по запросу: ". mysql_num_rows($result);
/**
* Если есть ряды, выводим таблицу
*/
if (mysql_num_rows($result) > 0) {
print "<table>";
print "<tr>";
print "<td>NickName</td>";
print "<td>RealName</td>";
print "<td>E-mail</td>";
print "</tr>";
$get = $_GET ["search"] ;
while ($row = mysql_fetch_array($result)) {
print "<tr>";
print "<td>";
print ($row ["unick"] ? preg_replace("/($get) /i", "<font color='red'>1</font>", $row ["unick"]):" ");
print "</td>";
print "<td>($row ["urealname"] ? $row ["urealname"]: " ") </td>";
print "<td>$row ["umail"] </td>";
print "</tr>";
}
print "</table>";
}
? >
Другие работы по теме:
записка
Цель работы — Разработка и программная реализация информационной систепмы социальной сети спортивного сайта с использованием современных технологий
Java для SMB
Бесспорно, java является одним из лидеров на рынке сложных корпоративных продуктов. Прекрасная масштабируемость и надежность - основные факторы этого успеха. Но стоит ли прибегать к такому мощному инструменту, когда масштабируемость не очень и важна?
Wiki как движок обычного сайта
Не секрет, что на настоящий момент традиционные cms переживают что-то типа кризиса. Новых технологий как бы и нет, новых направлений - тоже. В основном, cms тихо совершенствуются и "наращивают мясо" функциональности.
Как написать AJAX-приложение
Это два года назад AJAX был в диковинку (да и самого слова AJAX тогда ещё не выдумали). Теперь веб-приложения, страницы которых обновлялись на лету, в порядке вещей. Даже наоборот: без AJAX трудно представить себе некоторые сервисы.
Технічне створення Web-додатків
Огляд існуючих типів додатків, їх переваг та недоліків, принципів створення. HTML — стандартна мова розмітки документів для Web. Загальнi вiдомостi про Ajax. Мова JavaScript, проблема з налагодженням сценаріїв. Динамічне створення Flash-анімації.
Технология AJAX
Ajax - технология разработки Web-приложений c использованием кода на машине клиента для изменения данных на Web-сервере. Обновление Web-страницы без перезагрузки, прерывающей обмен данными. Методы и свойства объекта XMLHTTPRequest. Поле Select с поиском.
СУБД "Такси города Москва"
СУБД "Такси города Москва" предназначена для быстрого и эффективного поиска такси. Схематическое изображения структуры СУБД "Такси города Москва". Таблицы описания полей. Функциональные части БД: панель администрирования и пользовательский каталог.
Создание приложений на AJAX
Функции технологии Ajax разработки Web-приложений: выполнение HTTP-запросов в клиентской части и анализ ответа XML-сервера. Создание данных объекта XMLHttpRequest для разных браузеров. Обработка с помощью сервлета. Функциональность задач в Ajax.
ASP.NET Atlas AJAX в исполнении Microsoft
"ASP.NET Atlas" – AJAX в исполнении Microsoft Игорь Тамащук Введение Словосочетание "Web 2.0" знакомо сейчас, пожалуй, всем, кто более или менее внимательно следит за развитием Internet-а. И всем, наверное, знаком термин AJAX, который используется в этой концепции. В своей статье я расскажу о проекте Atlas – фреймворке для разработки AJAX web-приложений, который предлагает компания Microsoft разработчикам на ASP.NET.
Sophocles 3
Sophocles (pronounced /ˈsɒfəkliːz/ in English; Greek: Σοφοκλῆς, Sophoklēs, probably pronounced [sopʰoklɛ̂ːs]; c. 497/6 BC – winter 406/5 BC)[1] was the second of the three ancient Greek tragedians whose work has survived.
Troilus And Cressida Manipulations Of A Universal
Wolf Essay, Research Paper Tris Warkentin Shakespearean ComedyTroilus and Cressida, question 2 11/18/99 Manipulations of a “Universal Wolf” The focus of Troilus and Cressida on appetite as a type of human value, and hence a cause of action, causes a break in the Great Chain of Being, and thus the dissolution of order in both Troy and the Greek camp outside of it.
Troilus And Cressida Essay Research Paper The
Troilus And Cressida Essay, Research Paper The Bell Shakespeare Company s play Troilus+Cressida Directed by Michael Bogdanov is an example of the many re-skinned Shakespearean plays that emerge out of obscurity to challenge social mores in modern society. Troilus+Cressida, based in the 10 year war for a whore (Helen played by Helen Thompson) between the citizens of Troy and the Greeks, encompasses two contrasting notions of Love and War.
Ancient Greek Drama Essay Research Paper ORIGINS
Ancient Greek Drama Essay, Research Paper ORIGINS OF ANCIENT GREEK DRAMATheater was born in Attica, an Ionic region of Greece. It originated from the ceremonial orgies of Dionysos but soon enough its fields of interest spread to various myths along with historic facts. As ancient drama was an institution of Democracy, the great tragic poets Aeschylus, Sophocles, Euripides as well as the comedian Aristophanes elevated public debate and political criticism to a level of aesthetic achievement.
Toni Morrison And Sula Essay Research Paper
Toni Morrison is one of the most prolific authors of African American women novelist. She mostly focuses on issue of gender and community as in the story of Sula. Her contributions to African American literature are awarded many times in twentieth century.
Odyssey Essay Research Paper In the epic
Odyssey Essay, Research Paper In the epic novel of The Odyssey by Homer, the protagonist, Odysseus, display s the best example of a folktale hero. He isn t the son of any God or any supernatural being, and also he does not posses any immortal qualities. A call to an adventurous journey is what later on turns him into a hero.
Effect Of Acids And Bases Essay Research
Paper Experiments to Determine the Effect of Acids & Bases on Different Indicators and the pH of Common Cleaning Agents The aim of the first set of experiments is to find out and record the colour changes that are observed after a certain indicator is mixed with acids and bases to form a colour reaction. Once the selected indicator has been mixed with a acid that is both weak and strong and a base/alkali that is both weak and strong we are to record the colour and choose another indicator.
Friendships In Sula Essay Research Paper Confusing
Friendships In Sula Essay, Research Paper Confusing friendships and twisted love triangles is one of the themes in the book Sula by Toni Morrison. Sula and Nel had a very complex relationship, but in the end they both realized how precious friendship was to them and they overcame their differences.
Is 2
Is “Sula” A Tragic Novel? Essay, Research Paper Is “Sula” a tragic novel? I think it is. Because Sula grows up in an unusual family and many tragedies happen during her growth. Those kinds of tragedies we can even see it at the very beginning of the story. “Eva had married a man named BoyBoy and had three children: Hannah, the eldest, and Eva, whom she named after herself but called Pearl, and a son named Ralph whom she called Plum.” (32) After five years of their marriage, BoyBoy left Eva without leaving anything except $1.65, five eggs, three beets, and three children. “She was confused and desperately hungry.” (32) Sometimes, she will get help from her neighbors in the Medallion town.
Sula As A Defiant Selfexile Essay Research
Paper Sula in Tony Morrison’s Sula as a Defiant Self-Exile Morrison’s Sula, features a protagonist who shares her name with the book who has the decided attitude not to form social bonds in the Bottom, a black district inside, Medallion. Sectioned into two parts, the book divides between Sula Peace’s coming-of-age experience before she leaves the Bottom and her return to the Bottom as a mature woman.
Maya Angelou Essay Research Paper Maya AngelouMaya
Maya Angelou Essay, Research Paper Maya Angelou. Maya Angelou, born April 4, 1928 as Marguerite Johnson in St. Louis, was raised in segregated rural Arkansas. She is a poet, historian, author, actress, playwright, civil-rights activist, and director. She has been working at Wake Forest University in north Carolina since 1981.She has published ten best selling books and numerous magazine articles earning her Pulitzer Prize and National Book Award nomination.
Exploring The Novel Sula By Toni Morrison
Essay, Research Paper A Strong Woman is Outcast Melody Carter Women in 20th Cen. Lit. Prof. Fiona Paton Paper 2- Nov 10, 2000 In the novel Sula, by Toni Morrison we follow the life of Sula Peace through out her childhood in the twenties until her death in 1941. The novel surrounds the black community in Medallion, specifically “the bottom”.
Achilles Versus Hector Essay Research Paper Achilles
Achilles Versus Hector Essay, Research Paper Achilles vs. Hector The epic myth the Iliad, by Homer, portrayed the plight of a war between the Trojans and the Greeks. Achilles of Greece and Hector of Troy are the heroes that are crucial in the myth. The two main leaders of the war are Agamemnon and Paris who can be inadequate at times.
Iliad By Homer Essay Research Paper The
Iliad By Homer Essay, Research Paper The essay of Iliad, Homer finds a great tool in the simile. Just by opening the book in a random place the reader is undoubtedly faced with one, or within a few pages. Homer seems to use everyday activities, at least for the audience, his fellow Greeks, in these similes nearly exclusively.
Holocaust Essay Research Paper The Judgement of
Holocaust Essay, Research Paper The Judgement of Paris According to the legend, the chain of events that led to the Trojan War started at a royal wedding. Peleus, king of the Myrmidons, was marrying a sea nymph named Thetis. Many gods went to the the wedding, but Eris, daughter of Zeus, king of the gods, wasn’t invited because she was the goddess of discord and was going to cause trouble.
Interactions Of Gods And Men Essay Research
Paper Ian Ross Interactions of Gods and men Nothing can be more life changing than when a god chooses to interact with a mortal man. Much of Greek mythology describes the natures of these interactions. The Olympian Gods meddle with the mortals they rule over constantly, but what is the result for these interactions, and how do they impact the mortals? The question that this paper tries to address is what is the nature of these divine interaction, and how does each side truly perceive each other? The Gods and mortals interact in a variety of ways, but the true natures of these interactions truly describe how the ancient Greeks perceived their gods.
Greek Vase Painting Essay Research Paper Greek
Greek Vase Painting Essay, Research Paper Greek Vase Painting Greek vase painting is a very important part of Greek history. Greek vases provide us with important stories and information about ancient Greek life and mythology. This is acheaved through painted scenes on fired clay. These vases give us an idea of what life might have been like for ancient Greeks.
The Iliad Essay Research Paper THE ILIADBy
The Iliad Essay, Research Paper THE ILIAD By Aubrie Campbell The Iliad tells the story of the Trojan War, which lasted 10 years. The Grecians eventually won the war, but the outcome could have very easily shifted due to a quarrel between King Agamemnon and Achilles. Pride and anger is what the two men were fighting about.
Sophocles Essay Research Paper
In 495 B.C. there was a child born about a mile outside of Athens. This child was to be named Sophocles. He was a boy whose father was a wealthy merchant. He now had the opportunity to enjoy all of life’s greatest expectations in the Greek empire. Being that he was from a wealthy family, he had the chance to study all of the arts.
Sophocles Essay Research Paper Sophocles was born
Sophocles Essay, Research Paper Sophocles was born in Colonus, near Athens, c.497 B.C. Sophocles father was a wealthy armorer named Sophillus. When he reached adulthood he was already established as a great tragic playwright, and the citizens of Athens loved him. He was nicknamed Attic-bee by the Athenians because he could take pure honey from words.
Homers Ajax Essay Research Paper The relevance
Homer`s Ajax Essay, Research Paper The relevance that the themes of tragedy could have to issues affecting the city-state even in plays whose plots had ostensibly nothing to do with life in a