var ajax = new XMLHttpRequest(); ajax.onload = functionName; ajax.open("GET", url, true); ajax.send(); ... function functionName() { do something withthis.responseText
orthis.responseXML
; }
ajax.responseText
contains the data in plain text (a string)ajax.responseXML
is a parsed XML DOM tree object
var elms = node.getElementsByTagName("tag"); // get a group of nodes var text = node.firstChild.nodeValue; // get text inside a node var attrValue = node.getAttribute("name"); // get an attribute's value
Given this HTML file, write an accompanying recipe.js
that displays recipe information on the page with Ajax.
(sample solution)
GET
request to recipes.php with a parameter r
that has the value of the radio button, such as peas
.
recipes.php
are in XML format.
#main
div
with a h1
containing the titleimg
tag with the recipe's imageul
filled with the recipe's ingredients
The result XML from recipes.php
has the following structure (and some extra stuff):
<recipe> <information> <name>Peas with Butter</name> <image>https://webster.cs.washington.edu/cse154/sections/ajax/recipe/peas.jpg</image> <author>Vance McElmurry</author> <category>Entree</category> <description serves="4">A simple, but delicious frozen pea recipe.</description> </information> <ingredients> <item amount="1 lb">Frozen Peas</item> <item amount="1/4 cup">Water</item> <item amount="to taste">Salt</item> </ingredients> <directions> <step>Place the frozen peas and water in a microwavable bowl.</step> <step>Place the lid on th ebowl and cook in th emicorwave for 4 minutes.</step> </directions> </recipe>
You can view the solution javascript here.
If you finish the basic exercise, try adding more of the recipe info to the page, such as: