We've learned:
Today, we'll dynamically update the page by interacting with the server using Ajax.
By the end of today, you will be able to:
$.post(url, formdata, callback, datatype);
function cb(response) {
alert("done");
formatData(response);
};
{"title": "Dr. Zhivago",
"tt": 59113,
"year": 1965,
"stars": ["Omar Sharif",
"Julie Cristie",
"Geraldine Chaplin"],
"isGreat": true,
"director": {"name": "David Lean",
"nm": 180,
"birth": "1908-03-25"},
"IMDB rating": 8.0}
JSON.parse()
and JSON.stringify()
are widely supported by JavaScript
implementations.
I would answer your quiz questions, but there were none!
I've created an example of a Flask app that uses Ajax to get and send data. It's in /cs304collatz. I'll run that example, so we can try it out, and then we'll explore the code.
Compare these URLs:
I'll run the code in ~cs304/pub/downloads/ajax/
ajax
directory to your account:
cp -r ~cs304/pub/downloads/ajax/ ajax
collatz-app.py
file./getCollatzAjax/?num=25
and look
at the response
network
tab
to get some insight about the request and the response
addToList({in: 20, out: 10});
That updating of the DOM is incomplete. Shouldn't the new IN/OUT values replace the bold red numbers on the page? Do that.
Modify the response handler to update the page with the new values.
addToList
event handler. That
function is no longer well named. Maybe it should be renamed, or
the code should be re-factored. Think about this and discuss with
your partner.
My solution:
Add these two lines to addToList()
:
$("#result .x").text(obj.in);
$("#result .y").text(obj.out);
like this
function addToList(obj) {
if(obj.error) {
$("#errors").empty().html('Error: '+obj.err);
} else {
$("<li>")
.attr("data-num",obj.out)
.text("the number "+obj.in+" produces "+obj.out)
.appendTo("#collatzNumbers");
$("#result .x").text(obj.in);
$("#result .y").text(obj.out);
}
}
This is in addToList-improved.js
$.get()
or $.post()
, maybe in the JS
console.
It's useful to be able to navigate around the DOM. I'll give some examples using jQuery:
$(start).find(descendent_sel);
allows you to
search down from the start to the second selector. For
example:
var start = $("#result");
start.find(".x").text(42);
start.find(".y").text(21);
$(start).closest(ancestor_selector);
allows you to
search up for the first ancestor that matches the given
selector. Example:
var start = $("li")[3];
$(start).closest("ul");
We've come a long way! We learned