ajax basics
play

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 !=


  1. 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 != 200) { // Handle error ... return; } Raw text of response ... (also available as XML) var text = this.responseText; } CS 142 Lecture Notes: Ajax Slide 1

  2. JSON {name: "Alice", gpa: 3.5, friends: ["Bill", "Carol", "David"]} CS 142 Lecture Notes: Ajax Slide 2

  3. JSON Example ● 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"}, JSON {"advisor_id":"1","birth":"1990-04-16", Output "gpa":3.1,"grad":2012,"id":2, "name":"Jones"}, ... ] ● Javascript in browser: AJAX response (from XMLHttpRequest object) var students = eval(xhr.responseText); Slide 3

  4. CS 142 Lecture Notes: Cookies Slide 4

Recommend


More recommend