Getting started with AJAX開始使用的AJAX

by Joel Reyes on November 25, 2008 喬爾雷耶斯 2008年11月25日

網頁設計與開發

This guide provides some background info on Ajax, and then jumps right in and gets you started with examples.本指南提供一些背景信息的阿賈克斯隊,然後跳權和讓您開始使用的例子。

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已主要XMLHttpRequest的使用對象有一個良好的若干年來,但只是在最近才開始沒有獲得一些“名聲” 。 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. 很多騷動已經跟許多先進的web應用了網頁開發認為,流口水,並希望自己的網站上有同樣的確切先進的應用/功能。 But some of it also has to do with the group of people at AdaptivePath who have named this application Ajax 一些它也有這樣的一群人在AdaptivePath誰已命名此應用阿賈克斯

Ajax Beginners: What in the world is Ajax? 阿賈克斯初學者:什麼在世界上是阿賈克斯?

In a nutshell? 簡而言之? Well Ajax is a solution to web interfaces. 那麼Ajax是解決網絡接口。

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. 通常,網絡用戶輸入一些數據,或使一個簡單的選擇,並點擊一個按鈕,最後的選擇或輸入數據和發送數據到服務器。 The server hastily observes the data and sends back an entire new web page. 服務器匆忙觀察數據並傳回一個全新的網頁。 Having to reload a page every time you want to do something is very annoying, disjunctive and extremely time-consuming for the user. 在重新載入網頁每一次你想做些什麼是很煩人,析取和極其耗費時間的用戶。 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! resurfaces XMLHttpRequest的瀏覽器,服務器相互作用在幕後,讓使用者可以繼續玩同一頁上,甚至在內容網頁上所談論到服務器!

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. 與JavaScript我們一直能夠服務器端腳本沒有發生任何瀏覽器中使用一些經典的技巧我們的袖子。

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. 數據高速緩存的形式,以一個檔案, JavaScript的服務器上是好的,但是這通常不會返回任何有用的信息的JavaScript調用,因此其效力是非常有限的。 Ajax, however, can get a full parcel of data back from the script it calls. 阿賈克斯隊,但能充分包裹的數據備份的腳本要求。 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. 因此的“ XML ”的一部分的名字-這確實是有期待的種類,有點像的“爪哇”部分的J avaScript,因為返回的數據可以純文字或任何你想,如果X ML是不是你首選。

This alone opens up so many exciting possibilities. 僅此開闢了許多令人振奮的可能性。 Every form submission, every JavaScript event, and whatever else application, can now interact with server-side databases and processing power! 一切形式提交,每一個JavaScript的事件,不管其他人申請,現在可以與服務器端的數據庫和處理能力! Data retrieval, password authentication, image generation - you just name it, Ajax can activate it. 數據檢索,密碼驗證,圖像生成-你只是將它命名,阿賈克斯可以激活它。

Putting Ajax Into Practice 把阿賈克斯付諸實踐

The only thing that limits Ajax-enhanced web application is your imagination and by browser support. 唯一的限制阿賈克斯增強Web應用程序是你的想像力和瀏覽器的支持。 Mozilla-based browsers can do it, Safari, and newer versions of Internet Explorer, and Opera 8 but not Opera 7. 基於Mozilla的瀏覽器可以做到這一點, Safari和新版本的Internet Explorer和Opera 8日而不是歌劇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. 最好插槽替代的處事方式為用戶誰不作為機智在您希望對它們進行。 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. 此外, Internet Explorer會做的事有所不同(肯定是)從所有其他的瀏覽器,因此它非常重要的工作守則,以帳戶為越來越多80 %的人口依靠誰總管。

Now to the exciting part! 現在激動人心的一部分! 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. 讓我們產生一個簡單的應用程序,可以接受輸入的用戶,通過它的一些PHP的服務器上檢查這對一個數據庫,並返回結果到瀏覽器在使用中。 We assimilate it in three parts. 我們吸收它分為三個部分。

First, we need an HTML form. 首先,我們需要一個HTML表格。 As you’ can see below: 正如你可以看到如下:

 <html> 
  <head>的<head> 
  <title>Report</title>的<title>報告“ /標題” 
  <script type='text/javascript' src='xhr.js'></script> </head> <body> <form action="fallbackpage.php" method="post"> <script type='text/javascript' src='xhr.js'> “ /腳本” “ /頭” <body> <form action="fallbackpage.php" method="post"> 
  <p>Welcome, student. <p> ,歡迎學生。 Please enter your essay here:<textarea name="essay" id="essay">請輸入您的文章在這裡: <textarea name="essay" id="essay"> 
  </textarea> <input type="submit" name="submit" value="Submit" onClick="return “ /文本” “輸入類型= ”提交“名稱= ”提交“值= ”提交“ onClick = ”返回 
  grade(this.form.essay.value);">級( this.form.essay.value ) ; “ ” 
  </p> “ /人” 
  </form> “ /表格” 
  </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. 注意:對於用戶沒有適當的支持,我們的腳本命名為 xhr.js )的形式將只是向後退一頁 fallbackpage.php 。好吧,這是在那裡的JavaScript有,我們會把它緩慢。

 function grade(essay) {功能級(隨筆) ( 

The first thing we have to do is initialize the object. 首先,我們必須做的是初始化的對象。 There are two ways we must do this, for different browsers. 有兩種方法,我們必須做到這一點,為不同的瀏覽器。

 // Mozilla version / / Mozilla的版本 
     if (window.XMLHttpRequest) {如果( window.XMLHttpRequest ) ( 
         xhr = new XMLHttpRequest(); xhr =新的XMLHttpRequest的( ) ; 
     } 
     // IE version / / IE版本 
     else if (window.ActiveXObject) {否則,如果( window.ActiveXObject ) ( 
         xhr = new ActiveXObject("Microsoft.XMLHTTP"); xhr =新ActiveXObject ( “ Microsoft.XMLHTTP ” ) ; 
     } 

We then escape the user input to make it URL-safe: 然後,我們逃避用戶輸入,使其網址安全:

     essay=encodeURIComponent(essay);隨筆= encodeURIComponent (隨筆) ; 

and use the open method of the object to open a new connection to the PHP script: 並利用開放式的物體打開一個新連接到PHP腳本:

     xhr.open("POST","grade.php"); xhr.open ( “後” , “ 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: 該方法需要兩個論點:第一, HTTP方法( GET或POST ) ;第二,網址中的腳本。快速HTTP標頭的腳本聲稱為它獲得,然後傳送方法傳達的實際要求:

  xhr.setRequestHeader( xhr.setRequestHeader ( 
       'Content-Type', '內容類型' , 
       'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay);申請/的X WWW的形式urlencoded ;字符集= UTF - 8的' ) ; xhr.send (隨筆) ; 

This last step isn’t necessary for GET requests, wherein all the data can be contained in the query string of the URL. 這最後一步是沒有必要的GET請求,其中所有的數據可以在查詢字符串的網址。

Obtaining Final Results 獲得最後結果

We’re finally ready to see if the HTTP request we made worked. 我們終於願意看到,如果HTTP要求我們的工作。 The readyState property counts up from zero during the request, and shows 4 when the server page has been loaded successfully. readyState屬性 多達期間從零的請求,並顯示出第4當服務器頁面已經被成功加載。

  xhr.onreadystatechange=function() { xhr.onreadystatechange =函數( ) ( 
       if (xhr.readyState==4) {如果( 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. 如果確實是實際工作的要求,那麼我們能產出的服務器端腳本的查詢 responseText 財產,其中包含一個字符串。 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. 欲了解更多複雜的服務器腳本輸出,一個 responseXML屬性 ,它可以舉行一次完整文件對象的XML數據,是一種選擇也可以。

      grade = xhr.responseText;等級= xhr.responseText ; 
       alert ("Nice essay. Your grade is " + grade);警戒( “尼斯論文。您的等級是” +級) ; 
     } 
     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. 最後,第三個部分組成的PHP腳本,基本上生活在服務器上,並耐心等待的JavaScript來傳遞一些多汁的數據,使其能夠茁壯成長。 This example uses some PHP, but any language you like — Ruby, Perl, C, ASP — can address your needs as well. 這個例子使用了一些PHP ,但任何一種語言你喜歡-紅寶石語言,丙, A SP技術-可以解決您的需求,以及。 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. 核心的這個例子腳本是一種自然語言功能要求 grade_essay ( ) 年級學生的論文從1到100 ,但我會纂輯的一部分,以節省空間。

  <?php “ ?的PHP 
  function grade_essay($essay) {功能grade_essay ( $隨筆) ( 
       return strlen($essay);返回strlen ( $論述) ; 
  } 
  $essay = urldecode(implode(file('php://input'))); $隨筆= urldecode (爆(文件( '的PHP : / /輸入'))); 
  $grade = grade_essay($essay); $級= grade_essay ( $論述) ; 
  echo $grade;迴聲$級; 
  ?> ? “ 

The php://input grabs the POST data, which gets put into a string, decoded and passed to the clever grading algorithm. PHP : / /輸入 抓住POST數據,其中投入獲得一個字符串,解碼,並通過向聰明的分級方法。 The algorithm returns a numeric grade. 該算法返回一個數字等級。 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. 最後,我們只是輸出級的 迴聲 -通 常,這將顯示在瀏覽器中,但由於P HP腳本運行“的幕後”的字符串輸出僅僅是返回的J avaScript,要求它。 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 . 如果您需要結構化數據, XML文件將輸出的回波聲明只是以同樣的方式,但內容類型的輸出網頁基本上必須設置為 文本/ 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. 哪些用戶看到的是這樣的:她/他的散文類型的文本區中的瀏覽器,點擊提交,並在instants一個警告框彈出讓他/她最後年級的作文。 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. 看不見的,本文已發送到服務器,閱讀和評價,由一組PHP的精靈,並不可避免地返回一個年級,時無需重新加載頁面。 The user can modify her essay and resubmit it continuously. 用戶可以修改她的作文和重新不斷。

And that’s the general substance of the almost magical XMLHttpRequest object!這是一般的內容幾乎神奇的XMLHttpRequest對象! The example is pretty simple and straight forward, but the uses of the object can be highly, multi clever .的例子是非常簡單和直截了當,但使用的對象可高度,多聰明

For further inspiration and great examples of ingenious Ajax applications you can momentarily steer away from SimpleHelp.Net and visit 為進一步激勵和偉大的例子,巧妙的Ajax應用,您可以暫時擺脫SimpleHelp.Net訪問 iGoogle 的iGoogle , Pageflakes Pageflakes , Netflix Netflix的 and Netvibes Netvibes的 .


However, the data and functions that Ajax sends and acts out is simply up to you. 然而,數據和功能,發送和阿賈克斯的行為完全是由您決定。

Related Posts: 相關文章:
  • 30 Resources to Create Your Own Web 2.0 Site 30資源創建自己的Web 2.0網站
  • Increase your Linux/Unix Productivity: How to use crontab提高您的Linux / Unix的生產力:如何使用crontab
  • How to avoid phishing scams如何避免網絡釣魚詐騙
  • How to join (combine) multiple MP3 files in OS X如何加入(合併)多個MP3文件在OS X的
  • 20 Free RSS Readers Reviewed 20免費RSS閱讀器綜述
  • Get Simple Help tutorials just like this one in your email inbox every day - for free!獲取簡單的幫助教程就這樣一個在您的電子郵件收件匣每一天-是免費的! Just enter your email address below:只要輸入您的電子郵件地址如下:

    You can always opt out of this email subscription at any time.您可以隨時退出這個郵件訂閱在任何時候。


    Bookmark and Share 書籤和共享

    { 0 comments… 0評論... add one now現在添加一個 }

    Leave a Comment發表您的評論

    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> 您可以使用這些HTML標記和屬性: href="" title="">的<a <abbr title=""> <acronym title="">的<b> <blockquote cite=""> <cite>的<code> <del datetime="">的<em> <i> <q cite=""> <strike>的<strong>