Getting started with AJAX Primi passi con AJAX

by Joel Reyes on November 25, 2008 da Joel Reyes il 25 novembre 2008

Web design & dev

This guide provides some background info on Ajax, and then jumps right in and gets you started with examples. Questa guida fornisce alcune informazioni su Ajax, e poi a destra in salti e si è cominciato con degli esempi.

JavaScript has been the main use for XMLHttpRequest objects for a good number of years now, but only recently did it start to gain some “fame”. JavaScript è stato l'uso principale per gli oggetti XMLHttpRequest per un buon numero di anni a questa parte, ma solo di recente ha fatto iniziare a guadagnare qualche "fama". A lot of the ruckus has to do with the many advanced web applications having web developers that see it, drool and want their own site to have those same exact advanced applications/features. Parecchi dei prodotti prodotti Ruckus ha a che fare con le numerose applicazioni web avanzate aver sviluppatori web che vedere, drool e vogliono proprio sito per avere le stesse applicazioni avanzate esatto / funzioni. But some of it also has to do with the group of people at AdaptivePath who have named this application Ajax Ma alcuni di esso ha anche a che fare con il gruppo di persone a AdaptivePath che hanno chiamato questa applicazione Ajax

Ajax Beginners: What in the world is Ajax? Ajax principianti: Che cosa nel mondo è Ajax?

In a nutshell? In poche parole? Well Ajax is a solution to web interfaces. Beh Ajax è una soluzione di interfacce web.

Commonly, the web user enters some data or makes a simple choice, and clicks a button finalizing that choice or data entry and sends the data over to the server. Comunemente, il web utente inserisce alcuni dati o fa una scelta semplice, e clic di un pulsante che la finalizzazione scelta o l'immissione dei dati e invia i dati al server. The server hastily observes the data and sends back an entire new web page. Il server fretta osserva i dati e invia di nuovo un intero nuova pagina web. Having to reload a page every time you want to do something is very annoying, disjunctive and extremely time-consuming for the user. Dover ricaricare una pagina ogni volta che si vuole fare qualcosa è molto fastidioso, e molto disgiunta in termini di tempo per l'utente. XMLHttpRequest resurfaces the browser-server interaction to behind the scenes, so the user can just keep on playing with the same page, even while elements on the page are talking to the server! XMLHttpRequest riemerge il browser-server per l'interazione dietro le quinte, in modo che l'utente può solo continuare a giocare con la stessa pagina, anche se gli elementi sulla pagina si parla al server!

With JavaScript we’ve always been able to server-side script without anything happening in the browser by using a few classic tricks up our sleeves. Con JavaScript abbiamo semper stata in grado di server-side script senza nulla accade nel browser usando un classico alcuni trucchi su le maniche.

Caching form data to a file with JavaScript on a server is good, but this usually doesn’t return any useful information to the JavaScript that calls it, so its effectiveness is very limited. Caching dei dati sotto forma di un file con JavaScript su un server è buono, ma questo di solito non restituisce tutte le informazioni utili per il codice JavaScript che invita, quindi la sua efficacia è molto limitata. Ajax, however, can get a full parcel of data back from the script it calls. Ajax, tuttavia, può ottenere un pacco pieno di dati da script che chiama. Hence the “XML” part of the name - which really is just there for looks of sorts, kind of like the “Java” part of JavaScript, because the returned data can be plain text or whatever you like, if XML isn’t your preferred choice. Pertanto, la "XML" parte del nome - che in realtà è appena vi sembra di per genere, tipo di come la "Java" parte di JavaScript, perché l'ha restituito dati possono essere solo testo o qualunque cosa che ti piace, se XML non è il tuo scelta preferita.

This alone opens up so many exciting possibilities. Questo apre solo tanti eccitanti possibilità. Every form submission, every JavaScript event, and whatever else application, can now interact with server-side databases and processing power! Ogni forma di presentazione, ogni evento JavaScript, e qualunque altra applicazione, può ora interagire con il lato server database e potenza di elaborazione! Data retrieval, password authentication, image generation - you just name it, Ajax can activate it. Di reperimento dei dati, la password di autenticazione, l'immagine generazione - è solo il nome, Ajax può attivarla.

Putting Ajax Into Practice Mettere in pratica Ajax

The only thing that limits Ajax-enhanced web application is your imagination and by browser support. L'unica cosa che limita Ajax-enhanced applicazione web è la vostra immaginazione e il sostegno da parte del browser. Mozilla-based browsers can do it, Safari, and newer versions of Internet Explorer, and Opera 8 but not Opera 7. Mozilla-browser basati su puo 'farlo, Safari, e le versioni più recenti di Internet Explorer, Opera 8, ma non Opera 7. It’s best to slot in an alternative way of doing things for users who aren’t as witty as you’d hope for them to be. E 'meglio di bande orarie in modo alternativo di fare le cose per gli utenti che non sono come spiritoso come ti sentiresti di speranza per loro di essere. Also, Internet Explorer does things somewhat differently (most definitely) from all the other browsers, so it’s pretty essential to work the code to account for the irksome 80% of the population who rely on Explorer. Inoltre, Internet Explorer fa le cose un po 'diverso (più decisamente) da tutti gli altri browser, quindi è piuttosto essenziale per lavorare il codice per conto irksome per il 80% della popolazione che si basano su Explorer.

Now to the exciting part! Ora per la parte eccitante! Let’s generate a straightforward application that can accept input from the user, passes it to some PHP on the server that checks it against a database, and returns the result to the browser in use. Let's generare una semplice applicazione che può accettare input da parte dell'utente, si passa a circa il PHP sul server che si controlli nei confronti di un database e restituisce il risultato al browser in uso. We assimilate it in three parts. Abbiamo assimilare in tre parti.

First, we need an HTML form. In primo luogo, abbiamo bisogno di un form HTML. As you’ can see below: Come si 'può vedere qui di seguito:

 <html> 
  <head> 
  <title>Report</title> <title> rapporto </ title> 
  <script type='text/javascript' src='xhr.js'></script> </head> <body> <form action="fallbackpage.php" method="post"> <script type='text/javascript' src='xhr.js'> </ script> </ head> <body> <form action="fallbackpage.php" method="POST"> 
  <p>Welcome, student. <p> Benvenuto, studente. Please enter your essay here:<textarea name="essay" id="essay"> Inserisci il tuo saggio qui: <textarea name="essay" id="essay"> 
  </textarea> <input type="submit" name="submit" value="Submit" onClick="return </ textarea> <input type = "submit" name = "submit" value = "Invia" onClick = "return 
  grade(this.form.essay.value);"> grado (this.form.essay.value); "> 
  </p> </ p> 
  </form> </ form> 
  </body> </ body> 
  </html </ html 

Note: For users without proper support for our script ( named xhr.js ), the form will just simply submit to the fallback page at fallbackpage.php . Ok, this is where the JavaScript comes in, we’ll take it slow. Nota: Per gli utenti senza un adeguato sostegno per il nostro script (che prende il nome xhr.js), il modulo sarà semplicemente presentare alla pagina di ripiego a fallbackpage.php. Ok, questo è il codice JavaScript in cui entra in, ti prendo lento.

 function grade(essay) { funzione grado (saggio) ( 

The first thing we have to do is initialize the object. La prima cosa che dobbiamo fare è inizializzare l'oggetto. There are two ways we must do this, for different browsers. Ci sono due modi che dobbiamo fare questo, per i vari browser.

 // Mozilla version / / Versione di Mozilla 
     if (window.XMLHttpRequest) { if (window.XMLHttpRequest) ( 
         xhr = new XMLHttpRequest(); xhr = new XMLHttpRequest (); 
     } ) 
     // IE version / / IE versione 
     else if (window.ActiveXObject) { else if (window.ActiveXObject) ( 
         xhr = new ActiveXObject("Microsoft.XMLHTTP"); xhr = new ActiveXObject ( "Microsoft.XMLHTTP"); 
     } ) 

We then escape the user input to make it URL-safe: Abbiamo quindi sfuggire l'utente di ingresso per renderlo sicuro URL:

     essay=encodeURIComponent(essay); saggio = encodeURIComponent (saggio); 

and use the open method of the object to open a new connection to the PHP script: e l'uso del metodo aperto di oggetto per aprire una nuova connessione alla script PHP:

     xhr.open("POST","grade.php"); xhr.open ( "POST", "grade.php"); 

The method requires two arguments: first, the HTTP method (GET or POST) ; second, the URL of the script. A quick HTTP header asserts the script for what it’s getting, and then the send method conveys the actual request: Il metodo richiede due argomenti: in primo luogo, il metodo HTTP (GET o POST), in secondo luogo, l'URL dello script. Un rapido HTTP afferma lo script per ciò che la cosa sta andando, e quindi inviare il metodo effettivo trasmette la richiesta:

  xhr.setRequestHeader( xhr.setRequestHeader ( 
       'Content-Type', 
       'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay); 'application / x-www-form-urlencoded; charset = UTF-8'); xhr.send (saggio); 

This last step isn’t necessary for GET requests, wherein all the data can be contained in the query string of the URL. Questo ultimo passaggio non è necessario per richieste GET, in cui tutti i dati possono essere contenute nella stringa di ricerca di URL.

Obtaining Final Results Ottenere risultati finali

We’re finally ready to see if the HTTP request we made worked. Siamo finalmente pronti per vedere se la richiesta HTTP che abbiamo lavorato. The readyState property counts up from zero during the request, and shows 4 when the server page has been loaded successfully. La proprietà conta readyState da zero durante la richiesta, e mostra 4 quando il server pagina è stata caricata con successo.

  xhr.onreadystatechange=function() { Xhr.onreadystatechange = function () ( 
       if (xhr.readyState==4) { if (xhr.readyState == 4) ( 

If indeed the actual request worked, then we can get the output of the server-side script by querying the responseText property, which contains a string. Se infatti l'effettiva richiesta di lavoro, allora possiamo ottenere l'output del server-side script interrogando la responseText proprietà, che contiene una stringa. For more of a complex server script output, a responseXML property, which can hold a full document object of XML data, is an option also accessible. Per più di un complesso di script server di uscita, uno responseXML proprietà, che può contenere un intero documento oggetto di dati XML, è un'opzione anche accessibile.

      grade = xhr.responseText; = Xhr.responseText grado; 
       alert ("Nice essay. Your grade is " + grade); alert ( "saggio di Nizza. Il tuo voto è" + grado); 
     } ) 
     return false; return false; 
  } ) 

In conclusion, the third component consist of PHP script, which basically lives on the server and waits patiently for the JavaScript to pass it some juicy data so it can thrive. In conclusione, la terza componente consiste di script PHP, che vive essenzialmente sul server e attende con pazienza per il JavaScript per passare qualche succoso dati in modo che possa prosperare. This example uses some PHP, but any language you like — Ruby, Perl, C, ASP — can address your needs as well. Questo esempio usa un po 'di PHP, ma ogni lingua che ti piace - Ruby, Perl, C, ASP - può affrontare le vostre esigenze, come pure. The core of this example script is a natural-language function called grade_essay() that grades student essays from 1 to 100, but I will redact that part to conserve space. Il nucleo di questo script di esempio è un linguaggio naturale funzione chiamata grade_essay () che gradi studente saggi da 1 a 100, ma mi redact che parte per conservare spazio.

  <?php <? php 
  function grade_essay($essay) { funzione grade_essay ($ saggio) ( 
       return strlen($essay); ritorno strlen ($ saggio); 
  } ) 
  $essay = urldecode(implode(file('php://input'))); = $ saggio urldecode (implodere (file ( 'php: / / input'))); 
  $grade = grade_essay($essay); $ grado = grade_essay ($ saggio); 
  echo $grade; echo $ grado; 
  ?> 

The php://input grabs the POST data, which gets put into a string, decoded and passed to the clever grading algorithm. Php: / / input afferra il POST dei dati, che viene messo in una stringa, decodificati e passati al intelligente algoritmo di classificazione. The algorithm returns a numeric grade. L'algoritmo restituisce un grado numerico. Lastly, we just output the grade with echo - ordinarily, this would display in the browser, but since the PHP script is running “behind the scenes,” the string output is simply returned to the JavaScript that called it. Infine, abbiamo appena uscita con il grado di eco - normalmente, ciò visualizzazione nel browser, ma dato che la script PHP è in esecuzione "dietro le quinte", la stringa di uscita è semplicemente restituito al JavaScript che lo ha chiamato. If you need structured data, an XML document would be output with an echo statement in just the same way, but the content-type of the output page basically must be set to text/xml . Se avete bisogno di dati strutturati, un documento XML sarebbe uscita con una dichiarazione in eco alla stessa maniera, ma il contenuto-tipo di produzione fondamentalmente pagina deve essere impostato su text / xml.

What the user sees is this: She/He types their essay into the text area in the browser, clicks Submit, and within instants an alert box pops up giving him/her a final grade on the essay. Cosa vede l'utente è questa: Lei / Lui tipi di saggio in loro l'area di testo nel browser, i clic Invia, ed entro istanti una casella di avviso si apre con lui / lei un voto finale sul saggio. Invisibly, the essay has been sent to the server, read and evaluated by a team of PHP elves, and inevitably returned with a grade, without ever having to reload the page. Invisibile, il saggio è stato inviato al server, leggere e valutati da un team di PHP elfi, e inevitabilmente tornato con un grado di merito, senza mai dover ricaricare la pagina. The user can modify her essay and resubmit it continuously. L'utente può modificare il suo saggio e reinvia continuamente.

And that’s the general substance of the almost magical XMLHttpRequest object! E 'questa la sostanza generale di quasi il magico oggetto XMLHttpRequest! The example is pretty simple and straight forward, but the uses of the object can be highly, multi clever . L'esempio è piuttosto semplice e dritto in avanti, ma gli usi della oggetto può essere molto, più intelligente.

For further inspiration and great examples of ingenious Ajax applications you can momentarily steer away from SimpleHelp.Net and visit Per ulteriori grande ispirazione e geniale esempi di applicazioni AJAX è possibile orientare momentaneamente lontano da visita e SimpleHelp.Net iGoogle iGoogle , , Pageflakes Pageflakes , , Netflix NetFlix and e Netvibes Netvibes . .


However, the data and functions that Ajax sends and acts out is simply up to you. Tuttavia, i dati e le funzioni che invia e Ajax atti è semplicemente fuori da te.

Related Posts: Related Interventi:
  • 30 Resources to Create Your Own Web 2.0 Site 30 Risorse per creare il tuo sito Web 2.0
  • Increase your Linux/Unix Productivity: How to use crontab Aumenta la tua Linux / Unix Produttività: Come utilizzare crontab
  • How to avoid phishing scams Come evitare attacchi di phishing
  • How to join (combine) multiple MP3 files in OS X Come aderire (coniugare) molteplici file MP3 in OS X
  • 20 Free RSS Readers Reviewed 20 I lettori di feed RSS gratuito Recensito
  • Get Simple Help tutorials just like this one in your email inbox every day - for free! Ottieni Aiuto tutorial semplice come questo nella tua casella di posta tutti i giorni - gratuitamente! Just enter your email address below: Basta inserire il tuo indirizzo email qui sotto:

    You can always opt out of this email subscription at any time. È possibile scegliere di questa e-mail di iscrizione in qualsiasi momento.


    Bookmark and Share Favoriti e Condividi

    { 0 comments… (0 commenti ... add one now aggiungere uno ora } )

    Leave a Comment Lascia un tuo commento

    You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> È possibile utilizzare questi tag HTML e gli attributi: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>