50 likes | 160 Views
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; } ...
E N D
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; var document = this.responseXML; } State 4 means “done” Response available as raw text or XML CS 142 Lecture Notes: Ajax
JSON Example {name: "Alice", gpa: 3.5, friends: ["Bill", "Carol", "David"]} CS 142 Lecture Notes: Ajax
Name: Al Alfred Wang Alice Washington Allen Williams Allison McLean Alok Chandra Higher-Level AJAX Example <%= form.text_field(:userName) %> ... <div id="completionMenu">...</div> ... <%= observe_field( :form_userName, :update => "completionMenu", :url => {:action => "nameChoices"} ) %> class FooController < ApplicationController def nameChoices prefix = params[:form][:userName] ... compute names ... render :partial => "name_list", :layout => false end
Name: Al Alfred Wang Alice Washington Allen Williams Allison McLean Alok Chandra Higher-Level AJAX Example <%= form.text_field(:userName) %> ... <div id="completionMenu">...</div> ... <%= observe_field( :form_userName, :update => "completionMenu", :url => {:action => "nameChoices"} ) %> class FooController < ApplicationController def nameChoices prefix = params[:form][:userName] ... compute names ... render :partial => "name_list", :layout => false end