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. 난리의 많은 다양한 고급 웹 애플 리케이션, 잠꼬대는 그것을보고 자신의 사이트들을 똑같은 고급 애플 리케이션 / 기능을 원하는 웹 개발자가 함께 할 수있다. 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. 잘 아약스는 웹 인터페이스 솔루션입니다.

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! XMLHttpRequest를 막후, 그래서 사용자가 동일한 페이지를 그냥 가지고 노는에, 심지어하면서 얘기하는 페이지에 요소를 서버로 유지할 수 브라우저 - 서버의 상호 작용 resurfaces!

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. 우리는 항상 서버에서 자바 스크립트와 함께 할 수있는 게 아무것 - 쪽 스크립트를 브라우저에 우리의 소매를 몇 가지 전형적인 수법을 사용하여 일어나는 않고있다.

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. 자바 스크립트와 파일 서버에 폼 데이터 캐싱 좋은이다, 그러나 이것은 보통 자바 스크립트 그것 때문에 전화가 효과가 매우 제한되어있는 유용한 정보를 반환하지 않습니다. 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을"부분 - 정말 거기 그냥 일종의 모습, 친절을위한 자바 스크립트의 "자바"부분처럼 일반 될 수 있기 때문에 반환된 데이터를 텍스트 또는 무엇을 당신처럼, 만약 당신의 XML 아니다 선호하는 선택이다.

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! 모든 양식 제출, 모든 자바 스크립트 이벤트, 그리고 어떤 다른 애플 리케이션, 지금은 서버와 상호 작용할 수있는 - 사이드 데이터베이스와 프로세싱 파워! 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. 유일한 것은 한계가 아약스 - 향상된 웹 응용 프로그램을 귀하의 상상력과 브라우저를 지원하는 것입니다. Mozilla-based browsers can do it, Safari, and newer versions of Internet Explorer, and Opera 8 but not Opera 7. 모질라 - 기반 브라우저, 인터넷 익스플로러의 최신 버전, 그것을, Safari를 할 수 있으며 오페라 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 %를 차지하고 irksome.

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-override>로 리포트 </ 제목> 
  <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);"> 2 학년 (this.form.essay.value); "> 
  </p> </ 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. 참고 : 우리의 스크립트에 대한 적절한 지원없이 사용자를 위해 (), 양식을 그냥 단순히 대체 페이지의 이름 fallbackpage.php에 제출할 예정이다 xhr.js. 좋아,이 자리에서 자바 스크립트에 오면, 우리는 천천히 할테니까.

 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 / / 모질라 버전 
     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: 그렇다면 우리는 그것 - 안전 URL을 만들어 사용자가 입력 탈출 :

     essay=encodeURIComponent(essay); 에세이 = encodeURIComponent (에세이); 

and use the open method of the object to open a new connection to the PHP script: 그리고 PHP 스크립트에 새 연결을 열고 개체의 Open 메서드를 사용하는 경우 :

     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: 방법, HTTP 메소드 (GET 또는 POST); 2, 스크립트의 URL입니다. 빠른 HTTP 헤더, 그리고 그것을 어떤 방법으로 보내지고 스크립트에 대한 주장은 실제 요청을 전달하는 두 개의 인수 : 먼저이 필요합니다 :

  xhr.setRequestHeader( xhr.setRequestHeader ( 
       'Content-Type', '콘텐츠 - 타입', 
       'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay); '응용 프로그램 /는 x - www가 - 양식 - urlencode되고; 문자셋 = 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. 이 마지막 단계로, 여기서는 모든 데이터는 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에서 요청하는 동안, 건의 및 로드할 때 서버가 페이지를 성공적으로왔다 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. 는 XML 데이터의 전체 문서 개체를 저장할 수있는 복잡한 서버 스크립트 출력, responseXML에 재산가 더 들어있는 옵션도 이용할 수있다.

      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 스크립트는 자바 스크립트의 일부가 번성할 수있는 정말 맛있다는 데이터 패스로 이루어져있습니다. This example uses some PHP, but any language you like — Ruby, Perl, C, ASP — can address your needs as well. 이 예제지만 일부는 PHP를 사용하여 원하는 언어 - 루비, Perl, C와 ASP가 - 귀하의 요구 사항을 충족시킬뿐만 아니라 수있습니다. 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. 마지막으로, 우리는 단지 출력을 위해 echo 학년 - PHP 스크립트가 일반적으로 이후 "막후 실행되고, 이것이 브라우저에,하지만,"자바 스크립트 문자열을 출력하기만하면 그것라는 표시가 반환됩니다. 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 . 가능하면 그냥 같은 방식으로 출력 echo 구문이 될 것이지만, 출력 페이지의 콘텐츠 - 타입은 기본적으로 텍스트 / 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 넷플 릭스 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 자원 사이트에 귀하의 웹 2.0을 만들기 위해
  • Increase your Linux/Unix Productivity: How to use crontab 여러분의 리눅스 / 유닉스의 생산성 증가율 : crontab을 사용하는 방법
  • How to avoid phishing scams 피싱 사기를 방지하는 방법을
  • How to join (combine) multiple MP3 files in OS X 방법 () 운영 체제에서 X는 여러 개의 MP3 파일을 조합에 가입
  • 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 태그와 특성 : title="">은 <a href="" 사용할 수있습니다 <abbr title=""> <acronym title="">의 <b> <blockquote cite=""> <cite>의 <code> <del datetime="">의 <em>가 <i> <q cite=""> <strike>의 <strong>