最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Search XML with JavaScript and Display Results in Table - Stack Overflow

programmeradmin1浏览0评论

For my course, I have been asked to create a html page that has the functionality of allowing a user to enter the first name of a contact, which onsubmit, loads an xml file I previously created, loops through the contacts until it matches the first name entered by the user, and displays the contact information, except the email address, on the same page, in a table with headings and a <h1> displaying The contact details are:. If there is no match, there should be a <h2> that says The contact does not exist.

The following is my XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="Contact.xsl" ?>
<!DOCTYPE contact SYSTEM "contact.dtd">
<contact>
    <person>
        <name>
            <firstname>Bob</firstname>
            <lastname>Jones</lastname>
        </name>
        <phone>(02)44 42 45 63</phone>
        <address>
            <street>34 Highway Road</street>
            <city>Grovedale</city>
            <state>NSW</state>
            <postcode>3228</postcode>
            <email>[email protected]</email>
        </address>
    </person>
    <person>
        <name>
            <firstname>Gary</firstname>
            <lastname>Williams</lastname>
        </name>
        <phone>(02)44 41 87 56</phone>
        <address>
            <street>223 Yarra Avenue</street>
            <city>Branston</city>
            <state>NSW</state>
            <postcode>2317</postcode>
            <email>[email protected]</email>
        </address>
    </person>

I have tried a few things, but I have no idea how I would get the data to display in a table. The following is my XSL file which is how I assume they want the table to be shown, but with the results of the search.

<?xml version="1.0" encoding="ISO-8859-1"?><!-- DWXMLSource="Contact.xml" -->
<xsl:stylesheet version="1.0" xmlns:xsl="">
<xsl:template match="/">
<html>
<head>
<style>
body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
}
div {
    margin-left: 150px;
    margin-right: 20px;
    margin-top: 50px;
    width: 80%;
}
h1 {
    font-size: 24px;
    color: #F00;
}
.headings {
    background-color: #06F;
}
.data {
    background-color: #6F9;
}
.table {
    border: 2px solid #F00;
    width: 100%;
}
</style>
</head>
<body>
<div>
<h1>CONTACTS</h1>
    <table class="table">
        <tr class="headings">
            <th>First Name</th>
            <th>Last Name</th>
            <th>Street</th>
            <th>City</th>
            <th>State</th>
            <th>Postcode</th>
            <th>Email</th>
        </tr>
        <xsl:for-each select="contact/person">
        <tr class="data">
            <td><xsl:value-of select="name/firstname"/></td>
            <td><xsl:value-of select="name/lastname"/></td>
            <td><xsl:value-of select="address/street"/></td>
            <td><xsl:value-of select="address/city"/></td>
            <td><xsl:value-of select="address/state"/></td>
            <td><xsl:value-of select="address/postcode"/></td>
            <td><xsl:value-of select="address/email"/></td>
        </tr>
    </xsl:for-each>
</table>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

I have to use JavaScript to search the XML file and create a table displaying the results from the search.

The HTML I have is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ".dtd">
<html xmlns="">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Task 2</title>
<script language="JavaScript" type="text/javascript">
window.onload = loadIndex;
function loadIndex()
{
    if (document.implementation && document.implementation.createDocument)
    {
        xmlDoc = document.implementation.createDocument("", "", null);
        xmlDoc.load("Contact.xml");
    }
    else if (window.ActiveXObject)
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.load("Contact.xml");
    }
}
function searchIndex()
{
    if (!xmlDoc)
    {
        loadIndex();
    }
    var searchterm = document.getElementById("searchme").value;
    var allitems = xmlDoc.getElementsByTagName("firstname");
    results = new Array;
    for (var i=0;i<allitems.length;i++)
    {
        var name = allitems[i].lastChild.nodeValue;
        var exp = new RegExp(searchterm,"i");
        if ( name.match(exp) != null)
        {
            results.push(allitems[i]);
        }
    }
    showResults(results, searchterm);
}
function showResults(results, searchterm)
{
    //insert table data here to be displayed
}
</script>
</head>
<body>
First Name: <input type="text" name="firstname" id="searchme">
<br />
<input type="submit" value="Search" onClick="searchIndex(); return false;">
</body>
</html>

As you can see, I have no idea where to start. I know I would load the XML file, then gather the first name tag, then somehow pare the two then display the results.

I have seen the following, and this is similar to what I am after, but I cant get the results to display in a table.

Thanks for the help.

For my course, I have been asked to create a html page that has the functionality of allowing a user to enter the first name of a contact, which onsubmit, loads an xml file I previously created, loops through the contacts until it matches the first name entered by the user, and displays the contact information, except the email address, on the same page, in a table with headings and a <h1> displaying The contact details are:. If there is no match, there should be a <h2> that says The contact does not exist.

The following is my XML file:

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="Contact.xsl" ?>
<!DOCTYPE contact SYSTEM "contact.dtd">
<contact>
    <person>
        <name>
            <firstname>Bob</firstname>
            <lastname>Jones</lastname>
        </name>
        <phone>(02)44 42 45 63</phone>
        <address>
            <street>34 Highway Road</street>
            <city>Grovedale</city>
            <state>NSW</state>
            <postcode>3228</postcode>
            <email>[email protected]</email>
        </address>
    </person>
    <person>
        <name>
            <firstname>Gary</firstname>
            <lastname>Williams</lastname>
        </name>
        <phone>(02)44 41 87 56</phone>
        <address>
            <street>223 Yarra Avenue</street>
            <city>Branston</city>
            <state>NSW</state>
            <postcode>2317</postcode>
            <email>[email protected]</email>
        </address>
    </person>

I have tried a few things, but I have no idea how I would get the data to display in a table. The following is my XSL file which is how I assume they want the table to be shown, but with the results of the search.

<?xml version="1.0" encoding="ISO-8859-1"?><!-- DWXMLSource="Contact.xml" -->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<style>
body {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
}
div {
    margin-left: 150px;
    margin-right: 20px;
    margin-top: 50px;
    width: 80%;
}
h1 {
    font-size: 24px;
    color: #F00;
}
.headings {
    background-color: #06F;
}
.data {
    background-color: #6F9;
}
.table {
    border: 2px solid #F00;
    width: 100%;
}
</style>
</head>
<body>
<div>
<h1>CONTACTS</h1>
    <table class="table">
        <tr class="headings">
            <th>First Name</th>
            <th>Last Name</th>
            <th>Street</th>
            <th>City</th>
            <th>State</th>
            <th>Postcode</th>
            <th>Email</th>
        </tr>
        <xsl:for-each select="contact/person">
        <tr class="data">
            <td><xsl:value-of select="name/firstname"/></td>
            <td><xsl:value-of select="name/lastname"/></td>
            <td><xsl:value-of select="address/street"/></td>
            <td><xsl:value-of select="address/city"/></td>
            <td><xsl:value-of select="address/state"/></td>
            <td><xsl:value-of select="address/postcode"/></td>
            <td><xsl:value-of select="address/email"/></td>
        </tr>
    </xsl:for-each>
</table>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

I have to use JavaScript to search the XML file and create a table displaying the results from the search.

The HTML I have is as follows:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Task 2</title>
<script language="JavaScript" type="text/javascript">
window.onload = loadIndex;
function loadIndex()
{
    if (document.implementation && document.implementation.createDocument)
    {
        xmlDoc = document.implementation.createDocument("", "", null);
        xmlDoc.load("Contact.xml");
    }
    else if (window.ActiveXObject)
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.load("Contact.xml");
    }
}
function searchIndex()
{
    if (!xmlDoc)
    {
        loadIndex();
    }
    var searchterm = document.getElementById("searchme").value;
    var allitems = xmlDoc.getElementsByTagName("firstname");
    results = new Array;
    for (var i=0;i<allitems.length;i++)
    {
        var name = allitems[i].lastChild.nodeValue;
        var exp = new RegExp(searchterm,"i");
        if ( name.match(exp) != null)
        {
            results.push(allitems[i]);
        }
    }
    showResults(results, searchterm);
}
function showResults(results, searchterm)
{
    //insert table data here to be displayed
}
</script>
</head>
<body>
First Name: <input type="text" name="firstname" id="searchme">
<br />
<input type="submit" value="Search" onClick="searchIndex(); return false;">
</body>
</html>

As you can see, I have no idea where to start. I know I would load the XML file, then gather the first name tag, then somehow pare the two then display the results.

I have seen the following, and this is similar to what I am after, but I cant get the results to display in a table. http://www.dzone./snippets/simple-javascriptxml-based

Thanks for the help.

Share Improve this question edited Jun 10, 2013 at 3:17 Curley5959 asked Jun 10, 2013 at 3:04 Curley5959Curley5959 1192 gold badges3 silver badges12 bronze badges 4
  • where is the function searchIndex? – Arun P Johny Commented Jun 10, 2013 at 3:06
  • Nowhere at the moment. As I said. I dont have much idea where to start. Ill edit the above to what I think. – Curley5959 Commented Jun 10, 2013 at 3:10
  • Follow this. – kishoredbn Commented Jun 10, 2013 at 4:03
  • I was hoping for something a little bit more related to my problem. – Curley5959 Commented Jun 10, 2013 at 4:18
Add a ment  | 

3 Answers 3

Reset to default 1

The following is what I used to fix the issues I was having. One problem I was having is testing this locally. It will not work. This also is pending a message if no contact is found. I will update when I find the solution.

UPDATE: Solution found. See updated code below:

<script language="JavaScript" type="text/javascript">
function loadXMLDoc(dname)
{
    if (window.XMLHttpRequest)
    {
        xhttp=new XMLHttpRequest();
    }
    else
    {
        xhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET",dname,false);
    xhttp.send();
    return xhttp.responseXML;
} 
function searchXML()
{
    xmlDoc=loadXMLDoc("Contact.xml");
    x=xmlDoc.getElementsByTagName("firstname");
    input = document.getElementById("input").value;
    size = input.length;
    if (input == null || input == "")
    {
        document.getElementById("results").innerHTML= "Please enter a character or name!";
        return false;
    }
    for (i=0;i<x.length;i++)
    {
        startString = firstname.substring(0,size);
        if (startString.toLowerCase() == input.toLowerCase())
        {
            firstname=xmlDoc.getElementsByTagName("firstname")[i].childNodes[0].nodeValue;
            lastname=xmlDoc.getElementsByTagName("lastname")[i].childNodes[0].nodeValue;
            phone=xmlDoc.getElementsByTagName("phone")[i].childNodes[0].nodeValue;
            street=xmlDoc.getElementsByTagName("street")[i].childNodes[0].nodeValue;
            city=xmlDoc.getElementsByTagName("city")[i].childNodes[0].nodeValue;
            state=xmlDoc.getElementsByTagName("state")[i].childNodes[0].nodeValue;
            postcode=xmlDoc.getElementsByTagName("postcode")[i].childNodes[0].nodeValue;
            divText = "<h1>The contact details are:</h1><br /><table border=1><tr><th>First Name</th><th>Last Name</th><th>Phone</th><th>Street</th><th>City</th><th>State</th><th>Postcode</th></tr>" + "<tr><td>" + firstname + "</td><td>" + lastname + "</td><td>" + phone + "</td><td>" + street + "</td><td>" + city + "</td><td>" + state + "</td><td>" + postcode + "</td></tr>" + "</table>";
            break;
        }
        else
        {
            divText = "<h2>The contact does not exist.</h2>";
        }
    }
    document.getElementById("results").innerHTML= divText;
}
</script>

My html body:

<body>
First Name: <input type="text" name="firstname" id="input">
<br />
<input type="submit" value="Submit" onClick="searchXML()">
<br />
<br />
<div id="results">
</div>
</body>

I hope this can help someone else out.

 startString = firstname.substring(0,size);

Here, firstname is no where define before for loop, that's why giving below error.

Uncaught TypeError: Cannot read property 'substring' of undefined.

I referenced first name as a variable like this before the startString.

firstname = xmlDoc.getElementsByTagName("firstname")[i].childNodes[0].nodeValue;
startString = firstname.substring(0,size);

It worked great after that. Hope that helps!

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>