Sunteți pe pagina 1din 50

AJAX

Asynchronous
JavaScript
and XML
Ajax nu este o tehnologie, este un
ansamblu de tehnologii:

HTML sau XHTML pentru structurarea informaiilor;


CSS pentru prezentarea informaiilor;
Javascript pentru interactivitate i pentru procesarea
informaiilor prezentate;
Obiectul XMLHttpRequest pentru schimbul i
manipularea informaiilor ntr-o manier asincron cu
server-ul web;
XML este folosit de obicei pentru transferarea datelor
ntre server i client, dei orice format funcioneaz,
inclusiv HTML preformatat, text simplu etc.
Ajax nu este o tehnologie, este un
ansamblu de tehnologii:
Ideea de baz
AJAX este folosit pentru rennoirea
coninutului paginilor web asinhron prin
schimbarea doar unui fragment al paginii
fr rencarcarea paginii complet.

n procesul rennoirii fragmentului al paginii se


efectuiaz schimb de informaie ntre
browser i server.
Principiu de baz
AJAX
Browser
Server
Web-page
XML Javascript
Scrip
t

fragment
JavaScript 1
reacioneaz la un eveniment eveniment
schimb un fragment din pagin

<html> Oarecare text


<head> Click here
<script type="text/javascript">
function Executarea()
{
.... script ...
}
</script>
</head>
<body>
<div id="myDiv"><h2>Oarecare text</h2></div>

<button type="button" onclick=" Executarea()">Click here


</button>
</body>
</html>
JavaScript 1
reacioneaz la un eveniment eveniment
schimb un fragment din pagin

<html> Oarecare text


<head> Click here
<script type="text/javascript">
function Executarea()
{
document.getElementById("myDiv").innerHTML=Alt text;
}
</script>
</head>
<body>
<div id="myDiv"><h2>Oarecare text</h2></div>

<button type="button" onclick=" Executarea()">Click here


</button>
</body>
</html>
JavaScript 2
obiect
creeaz XMLHttpRequest object
<head>
<script type="text/javascript">
function Executarea()
{
creeaz XMLHttpRequest object

var xmlhttp; // se declara o variabila noua


if (window.XMLHttpRequest) // se verifica daca exista obiectul
{// code for Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();//se creeaza un obiect XMLHttpRequest
}
else
{// code for IE
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
} // se creeaza un obiect ActiveXObject
.... script ...
}
</script>
</head>
JavaScript 3
trimite
trimite request la server
function loadText()
creeaz XMLHttpRequest object

{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// se trimite request la server
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
JavaScript 3
trimite
trimite request la server

// exemplu
xmlhttp.open("GET","demo_get2.asp?fname=Andrei&lname=
Frunza",true);
xmlhttp.send();

// alt exemplu
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
JavaScript 3
trimite
trimite request la server
function loadText()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// se trimite request la server
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
4
ajax_info.txt server

AJAX va saluta!
AjAX
5
Server Response callback
processing
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 &&
xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML
=xmlhttp.responseText;
}
} // dac n request e fiierul textual
AjAX 6
Server Response (XML) DOM

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML=txt;
}
}
AjAX 4
Server Response (XML) server

<?xml version="1.0" encoding="ISO-8859-1" ?>


-<CATALOG>
-<CD>
<TITLE>Empire Burlesque</TITLE>
<ARTIST>Bob Dylan</ARTIST>
<COUNTRY>USA</COUNTRY>
<COMPANY>Columbia</COMPANY>
<PRICE>10.90</PRICE>
<YEAR>1985</YEAR>
</CD>
-<CD>
<TITLE>Hide your heart</TITLE>
<ARTIST>Bonnie Tyler</ARTIST>
<COUNTRY>UK</COUNTRY>
<COMPANY>CBS Records</COMPANY>
<PRICE>9.90</PRICE>
<YEAR>1988</YEAR>
AjAX 1
Server Response eveniment

<body>

<h2>My CD Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get
my CD collection</button>

</body>
AjAX 6
Server Response DOM

Rezultat:
My CD Collection:
Bob Dylan
Bonnie Tyler
Dolly Parton
Gary Moore
Eros Ramazzotti
Bee Gees
...
AjAX 5
onreadystatechange callback
event
Proprietatea onreadystatechange specific
funcia care va fi apelat fiecare data cnd se
schimb proprietatea readyState

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 &&
xmlhttp.status==200)
{
...
}
}
AjAX
5
onreadystatechange callback
event

Proprietatea readyState:

0: request not initialized


1: server connection established
2: request received
3: processing request
4: request finished and response is
ready
AjAX 5
onreadystatechange callback
event
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
...
}
}

Proprietatea status codul standard statusului HTTP:


200: "OK"
404: Page not found
Shema general de lucru cu
obiectul XMLHttpRequest
Crearea exemplarului obiectului
XMLHttpRequest.
Setarea de tratare a evenimentelor
onreadystatechange.
Conectarea cu server prin open.
Trimiterea interogrii prin send.
<html>
<head> Exemplu cu fisier textual
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} 2
else object
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() 6
{ DOM
if (xmlhttp.readyState==4 && xmlhttp.status==200)
5 {
callback document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
3
}
trimite
</script>
</head>
Exemplu cu fisierul XML

<body>

<div id="myDiv"><h2>Textul acesta va fi schimbat</h2></div>


<button type="button" onclick="loadXMLDoc()">Change
Content</button>

</body> 1
</html> eveniment
Exemplu cu fisierul XML

<html>
<head>
<script type="text/javascript">
function loadXMLDoc(url)
{
var xmlhttp;
if (window.XMLHttpRequest) 2
{// code for IE7+, Firefox, Chrome, Opera, Safari object
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
Exemplu cu fisier XML

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
5
document.getElementById('A1').innerHTML=xmlhttp.status;
callback
document.getElementById('A2').innerHTML=xmlhttp.statusText;
document.getElementById('A3').innerHTML=xmlhttp.responseText;
}
} 6
xmlhttp.open("GET",url,true); DOM
xmlhttp.send();
}
3
</script>
trimite
</head>
Exemplu cu fisier XML

<body>

<h2>Retrieve data from XML file</h2>


<p><b>Status:</b><span id="A1"></span></p>
<p><b>Status text:</b><span id="A2"></span></p>
<p><b>Response:</b><span id="A3"></span></p>
<button onclick="loadXMLDoc('note.xml')">Get XML data</button>

</body>
</html>
1
eveniment
Exemplu cu fisier XML

<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
4
server
Exemplu cu fisier XML

HTML fiier:

Retrieve data from XML file


Status: 1
Status text: event
Response:

Get XML data


Exemplu cu fisier XML

Dup apasarea butonului:


6
DOM
Retrieve data from XML file
Status:200
Status text:OK
Response:Tove Jani Reminder Don't forget me this weekend!

Get XML data


Proprietile obiectului
XMLHttpRequest:

readyState status (gata sau nu)


responseText textul transmis
responseXML obiect XML transmis
status HTTP status standard
statusText text ce descrie status (ok
sau not found)
Metodele obiectului
XMLHttpRequest:
open(<method>, <URL> [, <asyncFlag>[,
<userName>[, <password>]]]) conectarea cu
server;
send(<content>) trimiterea interogrii (pentru
metoda GET sring vid);
setRequestHeader(<label>, <value>)
setarea header-ului interogrii;
getResponseHeader(<headerLabel>)
obinerea valorii elementului header-ului;
getAllResponseHeaders( ) obinerea tuturor
valorilor elementelor header-ului;
abort( ) ntrerupe interogarea curent.
Exemplu cu un program PHP

<body>

<h3>Start typing a name in the input field below:</h3>


<form action="">
First name: <input type="text" id="txt1"
onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>
Exemplu cu un program PHP

<body>

<h3>Start typing a name in the input field below:</h3>


<form action="">
First name: <input type="text" id="txt1" 1
event
onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>

</body>
</html>
Exemplu cu un program PHP

<html>
<head>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
Exemplu cu un program PHP

<html>
<head>
<script type="text/javascript">
function showHint(str)
{
var xmlhttp; 2
if (str.length==0)
{ object
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
Exemplu cu un program PHP

xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
Exemplu cu un program PHP

xmlhttp.onreadystatechange=function() 5
callback
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
6
xmlhttp.open("GET","ajax_info.php?q="+str,true); DOM
xmlhttp.send();
}
</script> 3
</head> send
4
Exemplu cu un program PHP server

<?php for($i=0; $i<count($a); $i++)


// array with names {
$a[]="Anna"; if
$a[]="Brittany"; (strtolower($q)==strtolower(substr($a
$a[]="Cinderella"; [$i],0,strlen($q))))
... {
//get the q parameter from URL if ($hint=="")
{
$q=$_GET["q"];
$hint=$a[$i];
}
//lookup all hints from array if else
length of q>0 {
if (strlen($q) > 0) $hint=$hint." , ".$a[$i];
{ }
$hint=""; }
}
}
4
server
Exemplu cu un program PHP
// Set output to "no suggestion" if
no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}

//output the response


echo $response;
?>
Exemplu cu un program PHP
Dac JavaScript este blocat
if(window.XMLHttpRequest){
xmlObj = new XMLHttpRequest();
}
else if(window.ActiveXObject){
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
}
else { return; }
...
<a href="data.xml" title=Vizualizarea coninutului fiierului
XML" onclick="ajaxRead('data.xml');return false">
Avantajele AjAX

AJAX este independent de browser i


platforma utilizat;
AJAX este bazat pe standardele internet
AJAX micoreaz volumul datelor transferate
AJAX micoreaz volumul de lucru efectuat de
server
AJAX mrete viteza de rennoire a datelor pe
pagina web
Neajunsurile AjAX
Nu este integrat cu instrumentele browserului
Datele adugate pe pagin nu sunt accesibile
pentru sisteme de cautare
Contoare de accesare a paginilor nu sunt
valide
Creterea complexitii sitului
Se presupune JavaScript enabled
Aplicaii ce utilizeaz AJAX:

Google Maps
Gmail
Youtube
Facebook tabs
Mai multe exemple
http://test1.ru/ajax.html
http://test1.ru/ajax_3.html V
http://test1.ru/ajax_4.html
http://http://localhost/ajax_note_2015_MI141.html
http://http://localhost/ajax_jquery_note_IA142.html
http://http://test1.ru/ajax_rss.html
http://htmlweb.ru/ajax/example/
xmlhttp.onreadystatechange=function() Obinerea RSS
{ ajax_rss.html
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

document.getElementById("rssOutput").innerHTML=xmlhttp.respo
nseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>
<br />
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
getrss.php
<?php
//get the q parameter from URL
$q=$_GET["q"];

//find out which feed was selected


if($q=="Google")
{

$xml=("http://news.google.com/news?ned=us&topic
=h&output=rss");
}
elseif($q=="MSNBC")
{

$xml=("http://rss.msnbc.msn.com/id/3032091/device
/rss/rss.xml");
}

$xmlDoc = new DOMDocument();


$xmlDoc->load($xml);
getrss.php (continuare)
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')-
>item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel-
>getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br />");
echo($channel_desc . "</p>");
getrss.php (continuare)
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)-
>getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;

echo ("<p><a href='" . $item_link


. "'>" . $item_title . "</a>");
echo ("<br />");
echo ($item_desc . "</p>");
}
Rezultat

S-ar putea să vă placă și