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. 那么阿贾克斯是解决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. 通常,网络用户输入一些数据,或使一个简单的选项,并点击一个按钮,最后的选择或输入数据和发送数据到服务器上。 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 “ /资讯 

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属性 数量从0上升过程中的要求,并表明四日服务器页面已经被成功加载。

  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三十资源创建自己的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>