AJAX Basics xhr = new XMLHttpRequest(); xhr.onreadystatechange = - - PowerPoint PPT Presentation

ajax basics
SMART_READER_LITE
LIVE PREVIEW

AJAX Basics xhr = new XMLHttpRequest(); xhr.onreadystatechange = - - PowerPoint PPT Presentation

AJAX Basics xhr = new XMLHttpRequest(); xhr.onreadystatechange = xhrHandler; xhr.open("POST", url); xhr.send(postData); State 4 means done ... function xhrHandler() { if (this.readyState != 4) { return; } if (this.status !=


slide-1
SLIDE 1

CS 142 Lecture Notes: Ajax Slide 1

AJAX Basics

xhr = new XMLHttpRequest(); xhr.onreadystatechange = xhrHandler; xhr.open("POST", url); xhr.send(postData); ... function xhrHandler() { if (this.readyState != 4) { return; } if (this.status != 200) { // Handle error ... return; } ... var text = this.responseText; } State 4 means “done” Raw text of response (also available as XML)

slide-2
SLIDE 2

CS 142 Lecture Notes: Ajax Slide 2

JSON

{name: "Alice", gpa: 3.5, friends: ["Bill", "Carol", "David"]}

slide-3
SLIDE 3
  • Controller code:

Class StudentsController < ApplicationController def get_students @students = Student.find(:all) render :text => @students.to_json); end end [{"advisor_id":"2","birth":"1987-10-22", "gpa":3.9,"grad":2009,"id":1, "name":"Anderson"}, {"advisor_id":"1","birth":"1990-04-16", "gpa":3.1,"grad":2012,"id":2, "name":"Jones"}, ... ]

  • Javascript in browser:

var students = eval(xhr.responseText);

Slide 3

JSON Example

JSON Output AJAX response (from XMLHttpRequest object)

slide-4
SLIDE 4

CS 142 Lecture Notes: Cookies Slide 4