How to extract data from AJAX's responseText?
-
22-04-2021 - |
Question
When I use responseText, I get all the data. From <HTML>
to </HTML>
. How to I extract specific parts of it? For example, I have this code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tester</title>
</head>
<body>
<table>
<tr>
<td><a name="Name"></a>Name</td>
<td>John</td>
</tr>
<tr>
<td><a name="Email"></a>Email</td>
<td>john@aol.com</td>
</tr>
<tr>
<td><a name="Address"></a>Address</td>
<td>123 Elm Street</td>
</tr>
<tr>
<td><a name="City"></a>City</td>
<td>Los Angeles</td>
</tr>
<tr>
<td><a name="State"></a>State</td>
<td>CA</td>
</tr>
</table>
</body>
</html>
And Then I need to just extract like the city part Los Angeles. How would I go about doing this? I can't do responseText.getElementByTagName, or anything like that.
Here's the AJAX call:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var pageContents = xmlhttp.responseText;
document.getElementById("myDiv").innerText = pageContents;
}
}
xmlhttp.open("GET","content.html",false);
xmlhttp.send();
Solution
For a pure JavaScript solution, try (untested):
var city = responseXML.getElementsByName('City').parentNode.nextElementSibling.childNodes[0].getAttribute('textContent');
That said, a JavaScript library, like jQuery, to do the heavy lifting sure makes your code a lot easier to read (as well as cross-browser friendly).
OTHER TIPS
jQuery names this (sort of) easy:
alert($('table').find('tr').eq(3).find('td').eq(1).html())
---> Los Angeles
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow