AJAX & JavaScript

AJAX & Java Script

 

Ajax je tehnologija kojom se asinhrono (bez ponovnog ucitavanja strane) mogu zatraziti podaci sa servera I prikazati u delu strane predvidjene za to. Najveca prednost ove tehnologije je u ustedi u kolicini poslatih podataka, kako kod inicijalnog ucitavanja tako i svakog naknadnog.

Ajax je skup tehnologija ali se njegova implementacija svodi na kreiranje I manipulisanje posebnim JavaScript objektom XMLHttpRequest putem koga se ucitavaju podaci iz razlicitih vrsta dokumenata. Ti dokumenti mogu biti tekstualnog tipa, xml, html i JSON (Java Script Object Notation).

 

Ucitavanje TXT dokumenata

 

Pogledajmo jedan primer u kome cemo u div koji se nalazi unutar html fajla ucitati sadrzaj tekstualnog fajla demo.txt koriscenjem AJAX metode.

HTML fajl koji koristimo u primeru je prilicno jednostavan:

 

<!DOCTYPE html>

<html>

<head>

<title>Ajax i Java Script</title>

<script src=”TXTajax.js”></script>

</head>

<body>

<div id=”popuni”></div>

</body>

</html>

 

Jedino sto u njemu postoji su dva reda, jedan kojim ucitavamo TXTajax.js (fajl u kome cemo uraditi AJAX procesuiranje) I trenutno prazan div sa id-jem popuni u koji cemo ucitati sadrzaj fajla demo.txt. Fajl podaci.txt sadrzi samo nekoliko reci.

 

Java script fajl TXTajax.js izgledace ovako:

 

var zahtev = new XMLHttpRequest();

zahtev.open(‘GET’,’podaci.txt’);

zahtev.onreadystatechange = function(){

if(zahtev.status === 200 && zahtev.readyState === 4){

var izmeni = document.getElementById(‘popuni’);

izmeni.innerHTML = zahtev.responseText;

}

};

zahtev.send();

 

 

 

Ucitavanje XML dokumenata

 

HTML kod:

 

<!DOCTYPE html>

<html>

<head>

<title>Ajax i Java Script</title>

<meta charset=”utf-8″>

</head>

<body>

<div id=”popuni”></div>

<script src=”XMLajax.js”></script>

</body>

</html>

 

 

JS kod:

 

var zahtev = new XMLHttpRequest();

zahtev.open(‘GET’,’podaci.xml’);

 

zahtev.onreadystatechange = function(){

 

if(zahtev.status === 200 && zahtev.readyState === 4){

 

var autori = zahtev.responseXML.getElementsByTagName(‘author’);

 

var izlaz = “<ul>”;

for(var i = 0; i < autori.length; i++){

izlaz += “<li>” + autori[i].firstChild.nodeValue + “</li>”;

}

izlaz += “</ul>”;

document.getElementById(‘popuni’).innerHTML = izlaz;

}

}

zahtev.send();

 

 

 

XML document:

<?xml version=”1.0″?>

<catalog>

<book id=”bk101″>

<author>Gambardella, Matthew</author>

<title>XML Developer’s Guide</title>

<genre>Computer</genre>

<price>44.95</price>

<publish_date>2000-10-01</publish_date>

<description>An in-depth look at creating applications

with XML.</description>

</book>

<book id=”bk102″>

<author>Ralls, Kim</author>

<title>Midnight Rain</title>

<genre>Fantasy</genre>

<price>5.95</price>

<publish_date>2000-12-16</publish_date>

<description>A former architect battles corporate zombies,

an evil sorceress, and her own childhood to become queen

of the world.</description>

</book>

<book id=”bk103″>

<author>Corets, Eva</author>

<title>Maeve Ascendant</title>

<genre>Fantasy</genre>

<price>5.95</price>

<publish_date>2000-11-17</publish_date>

<description>After the collapse of a nanotechnology

society in England, the young survivors lay the

foundation for a new society.</description>

</book>

<book id=”bk104″>

<author>Corets, Eva</author>

<title>Oberon’s Legacy</title>

<genre>Fantasy</genre>

<price>5.95</price>

<publish_date>2001-03-10</publish_date>

<description>In post-apocalypse England, the mysterious

agent known only as Oberon helps to create a new life

for the inhabitants of London. Sequel to Maeve

Ascendant.</description>

</book>

<book id=”bk105″>

<author>Corets, Eva</author>

<title>The Sundered Grail</title>

<genre>Fantasy</genre>

<price>5.95</price>

<publish_date>2001-09-10</publish_date>

<description>The two daughters of Maeve, half-sisters,

battle one another for control of England. Sequel to

Oberon’s Legacy.</description>

</book>

<book id=”bk106″>

<author>Randall, Cynthia</author>

<title>Lover Birds</title>

<genre>Romance</genre>

<price>4.95</price>

<publish_date>2000-09-02</publish_date>

<description>When Carla meets Paul at an ornithology

conference, tempers fly as feathers get ruffled.</description>

</book>

<book id=”bk107″>

<author>Thurman, Paula</author>

<title>Splish Splash</title>

<genre>Romance</genre>

<price>4.95</price>

<publish_date>2000-11-02</publish_date>

<description>A deep sea diver finds true love twenty

thousand leagues beneath the sea.</description>

</book>

<book id=”bk108″>

<author>Knorr, Stefan</author>

<title>Creepy Crawlies</title>

<genre>Horror</genre>

<price>4.95</price>

<publish_date>2000-12-06</publish_date>

<description>An anthology of horror stories about roaches,

centipedes, scorpions and other insects.</description>

</book>

<book id=”bk109″>

<author>Kress, Peter</author>

<title>Paradox Lost</title>

<genre>Science Fiction</genre>

<price>6.95</price>

<publish_date>2000-11-02</publish_date>

<description>After an inadvertant trip through a Heisenberg

Uncertainty Device, James Salway discovers the problems

of being quantum.</description>

</book>

<book id=”bk110″>

<author>O’Brien, Tim</author>

<title>Microsoft .NET: The Programming Bible</title>

<genre>Computer</genre>

<price>36.95</price>

<publish_date>2000-12-09</publish_date>

<description>Microsoft’s .NET initiative is explored in

detail in this deep programmer’s reference.</description>

</book>

<book id=”bk111″>

<author>O’Brien, Tim</author>

<title>MSXML3: A Comprehensive Guide</title>

<genre>Computer</genre>

<price>36.95</price>

<publish_date>2000-12-01</publish_date>

<description>The Microsoft MSXML3 parser is covered in

detail, with attention to XML DOM interfaces, XSLT processing,

SAX and more.</description>

</book>

<book id=”bk112″>

<author>Galos, Mike</author>

<title>Visual Studio 7: A Comprehensive Guide</title>

<genre>Computer</genre>

<price>49.95</price>

<publish_date>2001-04-16</publish_date>

<description>Microsoft Visual Studio 7 is explored in depth,

looking at how Visual Basic, Visual C++, C#, and ASP+ are

integrated into a comprehensive development

environment.</description>

</book>

</catalog>

 

 

Ucitavanje JSON dokumenata

 

HTML kod:

<!DOCTYPE html>

<html>

<head>

<title>Ajax i Java Script</title>

<meta charset=”utf-8″>

</head>

<body>

<div id=”popuni”></div>

<script src=”JSONajax.js”></script>

</body>

</html>

 

 

JS kod:

var zahtev = new XMLHttpRequest();

zahtev.open(‘GET’,’podaci.json’);

 

zahtev.onreadystatechange = function(){

 

if(zahtev.status === 200 && zahtev.readyState === 4){

var sve= JSON.parse(zahtev.responseText);

 

var izlaz = “<ul>”;

for (var key in sve){

izlaz +=”<li>” + sve[key].name + “</li>”;

}

izlaz +=”</ul>”;

}

document.getElementById(‘popuni’).innerHTML= izlaz;

};

 

zahtev.send();

 

 

JSON document:

[

{

“name”:”Barot Bellingham”,

“shortname”:”Barot_Bellingham”,

“reknown”:”Royal Academy of Painting and Sculpture”,

“bio”:”Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot’s collection entitled \”The Un-Collection\” will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities – all of them, uniquely Barot, yet undeniably different”

},

{

“name”:”Jonathan G. Ferrar II”,

“shortname”:”Jonathan_Ferrar”,

“reknown”:”Artist to Watch in 2012″,

“bio”:”The Artist to Watch in 2012 by the London Review, Johnathan has already sold one of the highest priced-commissions paid to an art student, ever on record. The piece, entitled Gratitude Resort, a work in oil and mixed media, was sold for $750,000 and Jonathan donated all the proceeds to Art for Peace, an organization that provides college art scholarships for creative children in developing nations”

},

{

“name”:”Hillary Hewitt Goldwynn-Post”,

“shortname”:”Hillary_Goldwynn”,

“reknown”:”New York University”,

“bio”:”Hillary is a sophomore art sculpture student at New York University, and has already won all the major international prizes for new sculptors, including the Divinity Circle, the International Sculptor’s Medal, and the Academy of Paris Award. Hillary’s CAC exhibit features 25 abstract watercolor paintings that contain only water images including waves, deep sea, and river.”

},

{

“name”:”Hassum Harrod”,

“shortname”:”Hassum_Harrod”,

“reknown”:”Art College in New Dehli”,

“bio”:”The Art College in New Dehli has sponsored Hassum on scholarship for his entire undergraduate career at the university, seeing great promise in his contemporary paintings of landscapes – that use equal parts muted and vibrant tones, and are almost a contradiction in art. Hassum will be speaking on \”The use and absence of color in modern art\” during Thursday’s agenda.”

},

{

“name”:”Jennifer Jerome”,

“shortname”:”Jennifer_Jerome”,

“reknown”:”New Orleans, LA”,

“bio”:”A native of New Orleans, much of Jennifer’s work has centered around abstract images that depict flooding and rebuilding, having grown up as a teenager in the post-flood years. Despite the sadness of devastation and lives lost, Jennifer’s work also depicts the hope and togetherness of a community that has persevered. Jennifer’s exhibit will be discussed during Tuesday’s Water in Art theme.”

},

{

“name”:”LaVonne L. LaRue”,

“shortname”:”LaVonne_LaRue”,

“reknown”:”Chicago, IL”,

“bio”:”LaVonne’s giant-sized paintings all around Chicago tell the story of love, nature, and conservation – themes that are central to her heart. LaVonne will share her love and skill of graffiti art on Monday’s schedule, as she starts the painting of a 20-foot high wall in the Rousseau Room of Hotel Contempo in front of a standing-room only audience in Art in Unexpected Places.”

},

{

“name”:”Constance Olivia Smith”,

“shortname”:”Constance_Smith”,

“reknown”:”Fullerton-Brighton-Norwell Award”,

“bio”:”Constance received the Fullerton-Brighton-Norwell Award for Modern Art for her mixed-media image of a tree of life, with jewel-adorned branches depicting the arms of humanity, and precious gemstone-decorated leaves representing the spouting buds of togetherness. The daughter of a New York jeweler, Constance has been salvaging the discarded remnants of her father’s jewelry-making since she was five years old, and won the New York State Fair grand prize at the age of 8 years old for a gem-adorned painting of the Manhattan Bridge.”

},

{

“name”:”Riley Rudolph Rewington”,

“shortname”:”Riley_Rewington”,

“reknown”:”Roux Academy of Art, Media, and Design”,

“bio”:”A first-year student at the Roux Academy of Art, Media, and Design, Riley is already changing the face of modern art at the university. Riley’s exquisite abstract pieces have no intention of ever being understood, but instead beg the viewer to dream, create, pretend, and envision with their mind’s eye. Riley will be speaking on the \”Art of Abstract\” during Thursday’s schedule”

},

{

“name”:”Xhou Ta”,

“shortname”:”Xhou_Ta”,

“reknown”:”China International Art University”,

“bio”:”A senior at the China International Art University, Xhou has become well-known for his miniature sculptures, often the size of a rice granule, that are displayed by rear projection of microscope images on canvas. Xhou will discuss the art and science behind his incredibly detailed works of art.”

}

]

 

 

Kako bi ovo uradili sa jQuery sintaksom?

 

Zaprvao, jedino sto bi morali da promenimo je java script kod. On bi izgledao ovako:

 

$.getJSON(‘podaci.json’, function(podaci) {

var izlaz = ‘<ul>';

$.each(podaci, function(key, val){

izlaz +='<li>’ + val.name + ‘</li>';

});

izlaz +='</ul>';

$(‘#popuni’).html(izlaz);

});

 

Za slucaj da unutar diva sa id-jem popuni imamo jos neki tekst, umesto html(‘izlaz’) koristili bi append ili prepend metod.

 

 

 

 

Pozivanje AJAX-a u slucaju nekog dogadjaja

 

 

Ovako napisan kod izvrsava se prilikom ucitavanja strane. TO je bas bilo nesto sto nismo zeleli da se desava J. Da bi kod imao smisla, pogledacemo kako da ga iniciramo u slucaju nekog dogadjaja.

 

Ako pogledamo poslednji primer, narocito js kod, videcemo da se on uvek izvrsava, tj. odmah po pozivanju iz html-a. Da bi kontrolisali kada se kod izvrsava, sav kod cemo staviti unutar neke funkcije cije cemo iniciranje definisati kao klik na dugme. Za to nam treba I mala izmena u html delu, tj. dodavanje dugmeta na koje cemo kliknuti kako bi prouzrokovali izvrsenje koda.

 

HTML ce sada izgledati ovako:

<!DOCTYPE html>

<html>

<head>

<title>Ajax i Java Script</title>

<meta charset=”utf-8″>

</head>

<body>

Klikni za dobijanje spiska autora <input id=”klik” type=”button” value=”Klik”>

<div id=”popuni”></div>

<script src=”JSONajax.js”></script>

</body>

</html>

 

A JS kod:

klik.onclick = function (){

 

var zahtev = new XMLHttpRequest();

zahtev.open(‘GET’,’podaci.json’);

 

zahtev.onreadystatechange = function(){

 

if(zahtev.status === 200 && zahtev.readyState === 4){

var sve= JSON.parse(zahtev.responseText);

 

var izlaz = “<ul>”;

for (var key in sve){

izlaz +=”<li>” + sve[key].name + “</li>”;

}

izlaz +=”</ul>”;

}

document.getElementById(‘popuni’).innerHTML= izlaz;

};

 

zahtev.send();

 

}

 

 

 

Isto bi se moglo primeniti I u slucaju TXT i XML primera.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Zadatak: Kreiranje interaktivnog search-a sa slikama i tekstom

 

U ovom primeru kreiracemo search stranu koja ce podatke ucitavati iz JSON dokumenta a pomocu jQuery komandi suzavati search sa svakim otkucanim slovom.

 

Za ovaj zadatak imamo pripremljen JSON dokument i slike u folderu images. Sve ostalo cemo napraviti.

Prvo cemo pogledati HTML dokument koji predstavlja nasu search web stranicu. Kod je prilicno jednostavan, tj. sadrzi samo input polje i ucitava potrebne java script dokumente.

 

<!DOCTYPE html>

<html lang=”en”>

<head>

<title>Pretraga podataka AJAX</title>

<link rel=”stylesheet” type=”text/css” href=”mystyle.css”>

<meta charset=”utf-8″>

</head>

<body>

<div id=”searcharea”>

<label for=”search”>Label search</label>

<p>Enter a name or info about speaker</p>

<input type=”search” name=”search” id=”search” placeholder=”name or info”>

</div>

<div id=”update”></div>

<script src=”jquery.js”></script>

<script src=”script.js”></script>

</body>

</html>

 

U okviru diva sa id-jem update bice prikazani celokupni rezultati pretrage, pa nam njegov id treba u js dokumentu.

 

Dalje, imamo JSON dokument sa svim podacima. Njegov izgled je dat ispod.

[

{

“name”:”Barot Bellingham”,

“shortname”:”Barot_Bellingham”,

“reknown”:”Royal Academy of Painting and Sculpture”,

“bio”:”Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot’s collection entitled \”The Un-Collection\” will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities – all of them, uniquely Barot, yet undeniably different”

},

{

“name”:”Jonathan G. Ferrar II”,

“shortname”:”Jonathan_Ferrar”,

“reknown”:”Artist to Watch in 2012″,

“bio”:”The Artist to Watch in 2012 by the London Review, Johnathan has already sold one of the highest priced-commissions paid to an art student, ever on record. The piece, entitled Gratitude Resort, a work in oil and mixed media, was sold for $750,000 and Jonathan donated all the proceeds to Art for Peace, an organization that provides college art scholarships for creative children in developing nations”

},

{

“name”:”Hillary Hewitt Goldwynn-Post”,

“shortname”:”Hillary_Goldwynn”,

“reknown”:”New York University”,

“bio”:”Hillary is a sophomore art sculpture student at New York University, and has already won all the major international prizes for new sculptors, including the Divinity Circle, the International Sculptor’s Medal, and the Academy of Paris Award. Hillary’s CAC exhibit features 25 abstract watercolor paintings that contain only water images including waves, deep sea, and river.”

},

{

“name”:”Hassum Harrod”,

“shortname”:”Hassum_Harrod”,

“reknown”:”Art College in New Dehli”,

“bio”:”The Art College in New Dehli has sponsored Hassum on scholarship for his entire undergraduate career at the university, seeing great promise in his contemporary paintings of landscapes – that use equal parts muted and vibrant tones, and are almost a contradiction in art. Hassum will be speaking on \”The use and absence of color in modern art\” during Thursday’s agenda.”

},

{

“name”:”Jennifer Jerome”,

“shortname”:”Jennifer_Jerome”,

“reknown”:”New Orleans, LA”,

“bio”:”A native of New Orleans, much of Jennifer’s work has centered around abstract images that depict flooding and rebuilding, having grown up as a teenager in the post-flood years. Despite the sadness of devastation and lives lost, Jennifer’s work also depicts the hope and togetherness of a community that has persevered. Jennifer’s exhibit will be discussed during Tuesday’s Water in Art theme.”

},

{

“name”:”LaVonne L. LaRue”,

“shortname”:”LaVonne_LaRue”,

“reknown”:”Chicago, IL”,

“bio”:”LaVonne’s giant-sized paintings all around Chicago tell the story of love, nature, and conservation – themes that are central to her heart. LaVonne will share her love and skill of graffiti art on Monday’s schedule, as she starts the painting of a 20-foot high wall in the Rousseau Room of Hotel Contempo in front of a standing-room only audience in Art in Unexpected Places.”

},

{

“name”:”Constance Olivia Smith”,

“shortname”:”Constance_Smith”,

“reknown”:”Fullerton-Brighton-Norwell Award”,

“bio”:”Constance received the Fullerton-Brighton-Norwell Award for Modern Art for her mixed-media image of a tree of life, with jewel-adorned branches depicting the arms of humanity, and precious gemstone-decorated leaves representing the spouting buds of togetherness. The daughter of a New York jeweler, Constance has been salvaging the discarded remnants of her father’s jewelry-making since she was five years old, and won the New York State Fair grand prize at the age of 8 years old for a gem-adorned painting of the Manhattan Bridge.”

},

{

“name”:”Riley Rudolph Rewington”,

“shortname”:”Riley_Rewington”,

“reknown”:”Roux Academy of Art, Media, and Design”,

“bio”:”A first-year student at the Roux Academy of Art, Media, and Design, Riley is already changing the face of modern art at the university. Riley’s exquisite abstract pieces have no intention of ever being understood, but instead beg the viewer to dream, create, pretend, and envision with their mind’s eye. Riley will be speaking on the \”Art of Abstract\” during Thursday’s schedule”

},

{

“name”:”Xhou Ta”,

“shortname”:”Xhou_Ta”,

“reknown”:”China International Art University”,

“bio”:”A senior at the China International Art University, Xhou has become well-known for his miniature sculptures, often the size of a rice granule, that are displayed by rear projection of microscope images on canvas. Xhou will discuss the art and science behind his incredibly detailed works of art.”

}

]

 

 

 

 

 

 

Java Script dokument je ono sto nas zanima. Ovde ga dajemo u celosti a ispod pocinjemo sa objasnjenjima.

 

$(‘#search’).keyup(function(){

var searchField=$(‘#search’).val();

var myExp= new RegExp(searchField, ‘i’);

$.getJSON(‘data.json’, function(data){

var output = ‘<ul class=”searchresults”>';

$.each(data, function(key,val){

// ovaj if iskaz govori da li karaktere koje kucamo mozemo naci u tekstu name taga koji se trenutno ucitava ili njihove biografije

if(val.name.search(myExp) != -1 || val.bio.search(myExp) != -1){

output +='<li><h2>';

output +=val.name;

output +='</h2>';

output +='<img src=”images/’ + val.shortname + ‘_tn.jpg” alt=”‘ + val.name + ‘” >';

output +='<p>’ + val.bio + ‘</p>';

output +='</li>';

}

});

output +='</ul>';

$(‘#update’).html(output);

});

 

});

 

 

 

Java Script – deo po deo

 

 

Prva linija je kreirana u jQuery sintaksi i omogucava da se celokupan kod izvrsava u slucaju dogadjaja keyup (momenat nakon sto pritisnemo taster i otpustimo ga) i odnosi se na polje sa id-jem search –

 

$(‘#search’).keyup(function(){

 

Dalje, definisemo promenljivu koja ce hvatati tekst, tj. niz karaktera koje korisnik kuca. Njena vrednost se update-uje svaki put kada korisnik otkuca neko slovo iz prostog razloga jer se nalazi unutar keyup funkcije. Njena vrednost ce nam trebati kada budemo poredili da li se tekst koji kucamo nalazi u imenima (name svojstvo JSON dokumenta kao i u sekciji sa biografskim podacim – bio)

 

var searchField=$(‘#search’).val();

 

Nakon toga, kreiramo novu promenljivu koja proverava vrednosti promenljive i spremna je za kasnije uporedjivanje, tj. ovako napisana, ova promenljiva ima vrednost -1 ukoliko se pronadje poklapanje sa unetim nizom karaktera.’ i’ u Izrazu znaci da ne obraca paznju da li su mala ili velika slova u pitanju.

 

var myExp= new RegExp(searchField, ‘i’);

 

Sad sledi sekcija kojom se ucitavaju podaci iz JSON dokumenta prolazeci kroz petlju each (jQuery) i ispisuju se u vidu neuredjene liste <ul>. Podaci koje ucitavamo su iz JSON polja name, shortname i bio a linkove ka slikama gradimo kroz manipulisuci sa imenom i prezimenom osobe iz polja shortname.

 

$.getJSON(‘data.json’, function(data){

var output = ‘<ul class=”searchresults”>';

$.each(data, function(key,val){

 

 

Dalje imamo if iskaz koji proverava da li se u okviru stavke name i bio koje ucitava nalazi string koji je otkucan i ako jeste, on ima vrednost -1 i record se ispisuje. Ukoliko ga nema, petlja each ide na sledeci.

if(val.name.search(myExp) != -1 || val.bio.search(myExp) != -1){

output +='<li><h2>';

output +=val.name;

output +='</h2>';

output +='<img src=”images/’ + val.shortname + ‘_tn.jpg” alt=”‘ + val.name + ‘” >';

output +='<p>’ + val.bio + ‘</p>';

output +='</li>';

}

});

output +='</ul>';

 

Na kraju imamo red koji u div sa id-jem update smesta sve podatke uskladistene u promenljivu output koja ustvari predstavlja niz.

 

$(‘#update’).html(output);

Preporučite ovaj članak:
Email this to someoneShare on Google+Share on FacebookShare on LinkedIn