// document.getElementById("result").innerHTML = xmlhttp.responseText; //
Today, we would like to get and parse XML response with AJAX.
See employee.xml
Mike 20 mac iphone ipad James 25 mac iphone ipad Judy 18 mac iphone ipad
AJAX code
function getResult() { var xmlhttp = new XMLHttpRequest(); var name = document.getElementById("name").value; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // get root element var root = xmlhttp.responseXML.documentElement; // get all employee emelemts var employees = root.getElementsByTagName("employee"); var name = ""; var age = undefined; var output = ""; // get name and age for each employee element for (var i = 0; i < employees.length; i++) { name = employees[i].getElementsByTagName("name"); age = employees[i].getElementsByTagName("age"); output += name[0].firstChild.data + " is " + age[0].firstChild.data + "."; } document.getElementById("result").innerHTML = output; } } xmlhttp.open("GET", "employee.xml"); xmlhttp.send(); }
jQuery implementation
function getResult() { $.ajax({ url: 'employee.xml', dataType: 'xml', success: function(data) { $('#result').text(""); $(data).find('employees employee').each(function() { var name = $(this).find('name').text(); var age = $(this).find('age').text(); var id = $(this).attr('id'); var asset = $(this).find('asset').eq(0).text(); $('#result').append( $('<div />', { text: '(' + id + ') ' + name + ' is ' + age + ' - ' + asset + '.' }) ); }) }, error: function() { $("#result").text("failed to load."); } }); }Result
No comments:
Post a Comment