如何用Javascript将表单中的数据从HTML写到XML

时间:2022-03-02 13:56:14

This is an assignment from my class. What I need to do is create a registration page. When the user presses the submit button, I have take all the information on the form and write it to an existing XML file using Javascript. This is done on the client side, only through HTML, Javascript, and XML. By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves. Also, I'm not too familiar with Javascript, especially with the built in functions, if possible please explain what each line or method of code is doing.

这是我们班的作业。我需要做的是创建一个注册页面。当用户按下submit按钮时,我已经获取了表单上的所有信息,并使用Javascript将其写入到现有的XML文件中。这是在客户端完成的,仅通过HTML、Javascript和XML。顺便说一下,我的教授故意不教我们怎么做,因为他想让我们自己去研究。另外,我不太熟悉Javascript,特别是内置函数,如果可能的话,请解释一下代码的每一行或方法在做什么。

Let me begin, here's how my existing XML looks like:

首先,我的现有XML是这样的:

    <?xml version ="1.0" encoding="utf-8" ?>
    <!--GGFGFGFVBFVVVHVBV-->
    <PersonInfo>
      <Person Usrname="Bob111" Pswd="Smith111" personid="111" FirstName="Bob" LastName="Smith" DOB="01/01/1960" Gender="M" Title="Hello1"> 
      </Person>
    <!-- several more lines of <person> here --> 
    </PersonInfo>  

When saving the form data, it has to follow all the layout within , basically I would need Usrname, Pswd, personid, and so on.

保存表单数据时,它必须遵循内部的所有布局,基本上我需要Usrname、Pswd、personid等等。

Basically, from what I understand, I have to create the XML line "Person" from my registration page once I press submit. Then push it to the array that already have my XML information, then write over my XML document with the information on the array. My problem is, I have exactly no idea how to do that.

基本上,根据我的理解,当我按submit键时,我必须从注册页面创建XML行“Person”。然后将它推到已经拥有XML信息的数组中,然后用数组中的信息写XML文档。我的问题是,我完全不知道怎么做。

For those who wants to know how my registration page looks like, here it is:

对于那些想知道我的注册页面是怎样的人,这里是:

    <html>

    <head>
    <title>Registration</title>
    <link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
    </head>


    <body>

    <div class="form">
    <form id="Registration" action="" method="get">

    Username:<input type="text" name="usrname" maxlength="10"/> <br/>
    Password:<input type="password" name="pswd" maxlength="20"/> <br/>

    <hr>

    PersonID:<input type="text" name="PID" /> <br>

    <hr>

    First Name:<input type="text" name="fname"/> <br>
    Last Name:<input type="text" name="lname"/>

    <hr>

    DOB:<input type="text" name="dob" /> <br>

    <hr>

    Gender:<input type="text" name="sex" /> <br>

    <hr>

    Title:<input type="text" name="title" /> <br>

    <hr>

    Secret Question:<br>
    <select name="secret?">
    </select> <br>

    Answer:<input type="text" name="answer" /> <br> <br>

    <input type="submit" value="submit" />
    </form>
    </div>

    </body>

    </html>

By the way, I know certain information on my HTML document may not be worded properly, so do hope you guys don't mind. Also, I would also have to fix up my XML later by putting the answer to the secret question within later.

顺便说一下,我知道我的HTML文档中的某些信息可能写得不正确,所以希望你们不要介意。此外,我还必须在稍后对这个秘密问题给出答案,以修复我的XML。

Alright, thanks a lot in advance guys.

好的,非常感谢大家。

UPDATE!!!

更新! ! !

Here we go, I finally figured out how to create an XML document with Javascript, here's the code:

接下来,我终于弄明白了如何用Javascript创建XML文档,代码如下:

    var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';

    function SaveXML(UserData) 
    {   
        var file = fso.CreateTextFile(FILENAME, true);
        file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
        file.WriteLine('<PersonInfo>\n');

        for (countr = 0; countr < UserData.length; countr++) {
            file.Write('    <Person ');
            file.Write('Usrname="' + UserData[countr][0] + '" ');
            file.Write('Pswd="' + UserData[countr][1] + '" ');
            file.Write('PersonID="' + UserData[countr][2] + '" ');
            file.Write('FirstName="' + UserData[countr][3] + '" ');
            file.Write('LastName="' + UserData[countr][4] + '" ');
            file.Write('Gender="' + UserData[countr][5] + '" ');
            file.Write('DOB="' + UserData[countr][6] + '" ');
            file.Write('Title="' + UserData[countr][7] + '"');
            file.WriteLine('></Person>\n');
        } // end for countr

        file.WriteLine('</PersonInfo>\n');
        file.Close();

    } // end SaveXML function --------------------

    function LoadXML(xmlFile) 
    {
        xmlDoc.load(xmlFile);
        return xmlDoc.documentElement;
    } //end function LoadXML()

    function initialize_array() 
    {
        var person = new Array();
        var noFile = true;
        var xmlObj;
        if (fso.FileExists(FILENAME)) 
        {
            xmlObj = LoadXML(FILENAME);
            noFile = false;
            } // if
        else 
        {
            xmlObj = LoadXML("PersonXML.xml");
            //alert("local" + xmlObj);
            } // end if

        var usrCount = 0;
        while (usrCount < xmlObj.childNodes.length) 
        {
            var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
                                    xmlObj.childNodes(usrCount).getAttribute("Pswd"),
                        xmlObj.childNodes(usrCount).getAttribute("PersonID"),
                                    xmlObj.childNodes(usrCount).getAttribute("FirstName"),
                                    xmlObj.childNodes(usrCount).getAttribute("LastName"),
                                    xmlObj.childNodes(usrCount).getAttribute("Gender"),
                                    xmlObj.childNodes(usrCount).getAttribute("DOB"),
                                    xmlObj.childNodes(usrCount).getAttribute("Title"));
            person.push(tmpUsrs);
            usrCount++;
             }   //end while
        if (noFile == false)
            fso.DeleteFile(FILENAME);
        SaveXML(person);
    }   // end function initialize_array()  

What this code here is doing is that, it takes my original XML file and loads it up into an array so it can create a new XML file. Basically I got the creating the XML file part down, but still need help with the rest of my stuff.

这里的代码所做的是,它将我的原始XML文件加载到一个数组中,这样它就可以创建一个新的XML文件。基本上,我已经完成了创建XML文件部分的工作,但是仍然需要我的其他工作的帮助。

My goal is trying to take my form data and push it into my existing array, not overwrite it, add to it, so I can update my existing XML file with the new registration information. This is where I have absolutely no idea how to do. Some pointers would be nice.

我的目标是获取表单数据并将其推入现有数组中,而不是覆盖它,添加到其中,这样我就可以使用新的注册信息更新现有的XML文件。这是我完全不知道该怎么做的地方。一些指针会很好。

3 个解决方案

#1


5  

By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves.

顺便说一下,我的教授故意不教我们怎么做,因为他想让我们自己去研究。

Which should give you a hint about searching a bit more deeply. Anyhow, I'm not going to comment on every line, but I will offer some hints.

这会给你一个更深入搜索的提示。无论如何,我不会对每一行都进行评论,但我会提供一些提示。

 var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

That is a Microsoft proprietary way of creating an XML document and it is normally wrapped in try..catch as different ActiveXObjects are provided in different versions of IE. You also need to look for document.implementation.createDocument.

这是Microsoft创建XML文档的专有方式,通常在try中包装。在不同版本的IE中提供不同的activexobject对象。您还需要查找document.implementation.createDocument。

    //DEFINE LOAD METHOD
    function LoadXML(xmlFile)
    {
     xmlDoc.load(xmlFile);

You might want to check out the async parameter.

您可能需要检查async参数。

     xmlObj = xmlDoc.documentElement;
    }

    //declare & initialize array
    var arrPerson = new Array();

It is considered better practice to use an array literal: ... = [];

使用数组文字被认为是更好的实践:…=[];

    //initialize array w/ xml
    function initialize_array()
    {
    LoadXML("PersonXML.xml");
    var x = 0;
    while (x < xmlObj.childNodes.length)

Getting the length of xmlObj.childNodes on every loop is inefficient, consider storing the length and comparing with that value.

获得xmlObj的长度。每个循环上的子节点都是低效的,可以考虑存储长度并与该值进行比较。

    {
        var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"), 
                               xmlObj.childNodes(x).getAttribute("Pswd"), 
                               xmlObj.childNodes(x).getAttribute("FirstName"), 
                               xmlObj.childNodes(x).getAttribute("LastName"), 
                               xmlObj.childNodes(x).getAttribute("DOB"),
                               xmlObj.childNodes(x).getAttribute("Gender"),  
                               xmlObj.childNodes(x).getAttribute("Title"));

It is very inefficient to access xmlObj.childNodes(x) repeatedly. Store a reference and reuse it.

重复访问xmlObj.childNodes(x)非常低效。存储引用并重用它。

        arrPerson.push(tmpArr);

You could assign the values directly to arrPerson and get rid of tmpArr.

您可以直接将值分配给arrPerson并删除tmpArr。

        x++;   

Using a plain for loop will increment x for you.

使用普通的for循环将为您增加x。

    }
    }

    //Validation
    function LogInVal(objtxt)
    {
        if(objtxt.value.length == 0)
        {
            objtxt.style.background = "red";
            return 1;
        }

        else
        {
            objtxt.style.background = "white";
            return 0;
        }
    }

Not all browsers will let you style the background color of input elements.

并非所有浏览器都允许您对输入元素的背景色进行样式化。

    //main validation
    function MainVal(objForm)
    {
        var errmsg = "empty field";
        var errmsg2 = "Incorrect Username and Password";

You might want a better way of naming the error messages and relating them to other information for that message. An object might do the job.

您可能需要一种更好的方法来命名错误消息并将它们与该消息的其他信息关联起来。对象可以完成这项工作。

        var msg = "You have logged in successfully";
        var errCount = 0;

        var usrn = document.getElementById("usrname1").value;
        var pswd = document.getElementById("pswd1").value;

        errCount += LogInVal(objForm.usrname);
        errCount/*1*/ += LogInVal(objForm.pswd);

        initialize_array();    

        if (errCount != 0)
        {
            alert(errmsg);
            return false;
        }
        else if(authentication(usrn, pswd) == true)

The function authentication() returns true or false, so you don't need to compare it to anything, you can just test the returned value (i.e. there is no need for == true above).

函数authentication()返回true或false,因此不需要将它与任何东西进行比较,只需测试返回的值(即上面不需要= true)。

        {

            alert(msg);
            return true;
            setCookie('invalidUsr',' ttttt');
        }
        else
        {
            alert(errmsg2);
            return false;
        }
    }

Instead of showing alert messages one at a time in an alert, consider putting them in the document adjacent to the elements they relate to. That way the user can see the messaeg while fixing the error.

不要在警报中一次显示一个警报消息,考虑将它们放在与它们相关的元素相邻的文档中。这样用户就可以在修复错误时查看messaeg。

#2


2  

Isn't it cheating to ask us? Your implementation will probably only work in IE, I'd recommend using jQuery as it is impressively powerful at parsing XML.

问我们不是作弊吗?您的实现可能只在IE中工作,我推荐使用jQuery,因为它在解析XML方面非常强大。

I'm not sure why he wants you to write out XML as it's not very intuitive coming from JavaScript. You can do something like this via jQuery

我不知道他为什么要你写XML,因为它不是很直观的来自JavaScript。您可以通过jQuery做类似的事情

//I capture form submitevent

$('form').submit(function( ev ){
  ev.preventDefault(); //I keep form from submitting
  $( xmlDocument ).find('Person').attr({
    username: $("input[name=usrname]),
    password: $("input[name=pswd]),
    //and so on
  });

});

It's up to you on how you 'report' this xml file

这取决于您如何“报告”这个xml文件

#3


0  

Here i am sharing my experience in writing html form data to xml.

在这里,我将分享我编写html表单数据到xml的经验。

  1. Create one html file in one location (D:\\HtmlToXml.html).
  2. 在一个位置创建一个html文件(D:\ HtmlToXml.html)。
  3. And open it with Internet Explorer.
  4. 用ie打开。
  5. Then after provide information and click on submit button, then one file is created in the same directory with name example.xml.
  6. 然后,在提供信息并单击submit按钮之后,在同一个目录中创建一个名为example.xml的文件。
  7. If once an xml is created, then next time onwards on submit button click data will append to same xml file.
  8. 如果创建了xml,那么下次提交按钮时单击data将附加到相同的xml文件。

    <!DOCTYPE html>
    <html>
    <head>

        <title>Display Emp Details</title>

        <script type="text/javascript" language="javascript">

    	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        	var fso = new ActiveXObject("Scripting.FileSystemObject");	
        	var FILENAME='D:\\example.xml';



    function SaveXMLData()
    {
     	validations();
    }


    function createfile()
    {

    	var file;

        	var e1=document.getElementById('empName').value;
        	var p1=document.getElementById('empNumber').value;
        	var em1=document.getElementById('empEmail').value;
        	var d1=document.getElementById('empDate').value;

        	var tablemain = document.getElementById('tblmain');

    	if(fso.fileExists(FILENAME))
        	{
    		xmlDoc.load(FILENAME);
        		var lng;
        		lng=xmlDoc.getElementsByTagName("Details");

        		var xmlread= fso.OpenTextFile(FILENAME,1,true,0);

        		var x=xmlread.readAll();
        		var replace=x.replace('</Emp>','');
        		var sno=lng.length + 1;
        		file=fso.OpenTextFile(FILENAME,2,true);

        		file.writeLine(replace);

        		file.WriteLine('<Details category="'+sno+'">');
        		file.WriteLine('<SNo>'+sno+'</SNo>');
        		file.WriteLine('<Name>'+e1+'</Name>');
        		file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
        		file.WriteLine('<Emailid>'+em1+'</Emailid>');
        		file.WriteLine('<Date>'+d1+'</Date>');

        		file.WriteLine('</Details>');
        		file.WriteLine('</Emp>');
        		
    		alert('another file updated');
        	}
        	else
        	{

        		file= fso.CreateTextFile(FILENAME, true);
        		file.WriteLine('<?xml version="1.0" encoding="utf-8" ?>');
    		file.WriteLine('<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>');
        		file.WriteLine('<Emp>');
        		file.WriteLine('<Details category="1">');
        		file.WriteLine('<SNo>'+1+'</SNo>');
        		file.WriteLine('<Name>'+e1+'</Name>');
        		file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
        		file.WriteLine('<Emailid>'+em1+'</Emailid>');
        		file.WriteLine('<Date>'+d1+'</Date>');

        		file.WriteLine('</Details>');
        		file.WriteLine('</Emp>');     

    		alert('file updated');
        	}

    	<!-- displayData();-->

    	document.getElementById('empName').value='';
    	document.getElementById('empNumber').value='';
    	document.getElementById('empEmail').value='';
    	document.getElementById('empDate').value='';

    addRow('tablemain');
    	file.close();
    }

         
    function validations() 
    {
    	var emp1=document.getElementById('empName').value; 
            var letters = /^[\s A-Za-z]+$/; 
            if(emp1!="")
            {
            	if(emp1.match(letters)) 
              	{
    	    		allnumeric();
              	}
              	else 
    	        {
              		alert('Please input alphabet characters only'); 
              		return false; 
              	}
            }
    	else
    	{
    	  	alert('Please Enter Name.');
     	}
    }

            
    <!--For checking Email-->

    function checkemail()
    {
    	var email = document.getElementById('empEmail');
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    	if(email.value!="")
    	{
            	if (!filter.test(email.value)) 
    		{
            		alert('Please provide a valid email address');
            		return false;
            	}
                    else
                    {
                    	DateValidation();
                    }
           	}     
    	else
    	{
    		alert('Please Enter Email.');
    	}
    }


    <!--For checking Date Format-->

    function DateValidation()
    {
        	var date=/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}$/;
        	var empDate=document.getElementById("empDate");

    	if(empDate.value!="")
          	{
    	    	if(empDate.value.match(date))
    	    	{
    	    		createfile();
    	    	}
    	    	else
    		{
        	     		alert("Please provide valid date : DD-MM-YY(YYYY)");
    			return(false);
    	    	}
          	}
    	else
    	{
    		alert('Please Enter Date.');
    	}
    }


    <!--For checking phone number-->

    function allnumeric() 
    {
    	var numbers=/^\d{10}$/;
        	var empNumber=document.getElementById("empNumber");
    	if(empNumber.value!="")
    	{
    		if(empNumber.value.length=="10")
    		{
        			if(empNumber.value.match(numbers))
        			{
           				checkemail();
        			}
        			else
    			{
    	    			alert("Phone number should be numeric");
        				return(false);
    			}
    		}
    		else
    		{
    			alert('Phone Number should be like: 9876543210');
    		}
    	}
    	else
    	{
    		alert('Please Enter Phone Number.');
    	}
    }



    function addRow(id) 
    {

        if(fso.fileExists(FILENAME))
        {

    	xmlDoc.load(FILENAME);
        	var x;
        	x=xmlDoc.getElementsByTagName("Details");

            var table = document.getElementById('tbl');        



    	var nxtbtn= document.getElementById("btnnext");
    	var prvbtn=document.getElementById("btnprev");
    	nxtbtn.disabled=true;
    	prvbtn.disabled=true;
    	if(x.length >5)
    	{
    		nxtbtn.disabled=false;
    	}
    	var j=0;k=5;
    	if(k>x.length)
    	{k=x.length;}

    	var store=document.getElementById("txtstore");
    	var maxval=document.getElementById("txtmax");

    	if(id=="btnprev")
    	{        
    		if((store.value % k)==0)
    		{
    			store.value = store.value - k ;
    			if(store.value>0)
    			{
    				j = parseInt(store.value);
    				k += parseInt(store.value);
    			}
    		}
    		else
    		{
    			store.value =store.value - (store.value % k) ;

    			if(store.value >0)
    			{
    				j = store.value - k;
    				k = store.value;
    			}
    	
    		}
    	
    		if(j > 0)
    		{
    			prvbtn.disabled=false;
    		}

    	}
    	if(id=="btnnext")
    	{
    		if(store.value==0)
    		{
    			store.value=table.rows.length;
    		}
    		else if(store.value <0)
    		{
    			store.value=maxval.value;
    		}
    		prvbtn.disabled=false;
    	    	if(store.value >=k)
    		{
    			j +=parseInt(store.value);
    			k +=parseInt(store.value);
    			if(k >= x.length)
    			{
    				k=x.length;
    				nxtbtn.disabled = true;
    				prvbtn.disabled = false;
    			}
    		}
    	}

    	table.innerHTML = "";
    	var rowCount = 0;

         	for (i=j;i<k;i++)
    	{
         
            	var row = table.insertRow(rowCount);

    	        var cell1 = row.insertCell(0);
            	var element1 = document.createElement("input");
    	        element1.type = "checkbox";
    	        element1.id =  "id2" ;
            	cell1.appendChild(element1);

    	        // Create label
            	var label = document.createElement("label");
    	        label.htmlFor =  "id2" ;
            	cell1.appendChild(label);

    	        var cell2 = row.insertCell(1);
            	cell2.innerHTML = x[i].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;

    	        var name = row.insertCell(2);
            	var elname =document.createElement("input");
    	        elname.type = "text";
    		elname.readOnly=true;
    		elname.value=x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
    	        name.appendChild(elname);

    	        var phnno = row.insertCell(3);
            	var elphn =document.createElement("input");
    	        elphn.type = "text";
    		elphn.readOnly=true;
    		elphn.value=x[i].getElementsByTagName("PhoneNumber")[0].childNodes[0].nodeValue;
            	phnno.appendChild(elphn);

    	        var email = row.insertCell(4);
            	var elemail =document.createElement("input");
    	        elemail.type = "text";
    		elemail.readOnly=true;
    		elemail.value=x[i].getElementsByTagName("Emailid")[0].childNodes[0].nodeValue;
            	email.appendChild(elemail);

    	        var date = row.insertCell(5);
            	var eldate =document.createElement("input");
    	        eldate.type = "text";
    		eldate.readOnly=true;
    		eldate.value=x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue;
            	date.appendChild(eldate);
    	
    		rowCount +=1;
         	}
    	maxval.value=x[table.rows.length - 1].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;

    	if(id=="btnprev")
    	{
    	 store.value =store.value - 5;
    	}
    	 else
    	{
        	 store.value =parseInt(k);
    	}
       }
    }

        </script>
    </head>

    <body onload="addRow('tbl')">

    	<form id="empForm" action="" method="get">

        	<p><b>Emp Registration:</b></p>

        	<table>
        		<tr>
        			<td>Name:</td>
        			<td><input type="text" id="empName" maxlength="25"/></td>
        		</tr>
        		<tr>
        			<td>Phone Number:</td>
        			<td><input type="text" id="empNumber" maxlength="10"/></td>
        		</tr>
    	    	<tr>
        			<td>EmailId:</td>
        			<td><input type="text" id="empEmail"/></td>
        		</tr>
        		<tr>
        			<td>Date:</td>
        			<td><input type="text" id="empDate" maxlength="10"/></td>
        		</tr>
        		<tr>
        			<td align="center">
    			<input type="button" value="Submit" onclick="SaveXMLData()"/></td>
        			<td>
    			<input type="button" value="Show Data" id="show" onclick="displayData(this.id)" style="display:none;"/></td>
        		</tr>
        	</table>
    	<!-- <table><tr><td><input type="button" onclick="displayData(this.id)" value="Prev" id="prev" disabled="disabled"></td>
    	   <td><input type="button" onclick="displayData(this.id)" value="Next" id="next" disabled="disabled"></td></tr></table> -->

     	<div id='displaydatadiv'>	
        	</div>
    	<!-- <INPUT type="button" value="Add Row" onclick="addRow('tbl')" /> -->
    	
    	<div style="height: 135px; width:650px; background-color: Lavender;" >
    		<TABLE id="tbl" width="350px">    
      		</TABLE>
    	</div>
    	<table id="tblmain" border="1" style="display:true" ></table>
    		<input type="button" id="btnprev" value="Prev" onclick="addRow(this.id)" disabled="disabled">
    		<input type="button" id="btnnext" value="Next" onclick="addRow(this.id)" disabled="disabled">

    		<input type="hidden" id="txtstore" style="display:none;">
    		<input type="hidden" id="txtmax" style="display:none;">

    </body>
    </html>
        

#1


5  

By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves.

顺便说一下,我的教授故意不教我们怎么做,因为他想让我们自己去研究。

Which should give you a hint about searching a bit more deeply. Anyhow, I'm not going to comment on every line, but I will offer some hints.

这会给你一个更深入搜索的提示。无论如何,我不会对每一行都进行评论,但我会提供一些提示。

 var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

That is a Microsoft proprietary way of creating an XML document and it is normally wrapped in try..catch as different ActiveXObjects are provided in different versions of IE. You also need to look for document.implementation.createDocument.

这是Microsoft创建XML文档的专有方式,通常在try中包装。在不同版本的IE中提供不同的activexobject对象。您还需要查找document.implementation.createDocument。

    //DEFINE LOAD METHOD
    function LoadXML(xmlFile)
    {
     xmlDoc.load(xmlFile);

You might want to check out the async parameter.

您可能需要检查async参数。

     xmlObj = xmlDoc.documentElement;
    }

    //declare & initialize array
    var arrPerson = new Array();

It is considered better practice to use an array literal: ... = [];

使用数组文字被认为是更好的实践:…=[];

    //initialize array w/ xml
    function initialize_array()
    {
    LoadXML("PersonXML.xml");
    var x = 0;
    while (x < xmlObj.childNodes.length)

Getting the length of xmlObj.childNodes on every loop is inefficient, consider storing the length and comparing with that value.

获得xmlObj的长度。每个循环上的子节点都是低效的,可以考虑存储长度并与该值进行比较。

    {
        var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"), 
                               xmlObj.childNodes(x).getAttribute("Pswd"), 
                               xmlObj.childNodes(x).getAttribute("FirstName"), 
                               xmlObj.childNodes(x).getAttribute("LastName"), 
                               xmlObj.childNodes(x).getAttribute("DOB"),
                               xmlObj.childNodes(x).getAttribute("Gender"),  
                               xmlObj.childNodes(x).getAttribute("Title"));

It is very inefficient to access xmlObj.childNodes(x) repeatedly. Store a reference and reuse it.

重复访问xmlObj.childNodes(x)非常低效。存储引用并重用它。

        arrPerson.push(tmpArr);

You could assign the values directly to arrPerson and get rid of tmpArr.

您可以直接将值分配给arrPerson并删除tmpArr。

        x++;   

Using a plain for loop will increment x for you.

使用普通的for循环将为您增加x。

    }
    }

    //Validation
    function LogInVal(objtxt)
    {
        if(objtxt.value.length == 0)
        {
            objtxt.style.background = "red";
            return 1;
        }

        else
        {
            objtxt.style.background = "white";
            return 0;
        }
    }

Not all browsers will let you style the background color of input elements.

并非所有浏览器都允许您对输入元素的背景色进行样式化。

    //main validation
    function MainVal(objForm)
    {
        var errmsg = "empty field";
        var errmsg2 = "Incorrect Username and Password";

You might want a better way of naming the error messages and relating them to other information for that message. An object might do the job.

您可能需要一种更好的方法来命名错误消息并将它们与该消息的其他信息关联起来。对象可以完成这项工作。

        var msg = "You have logged in successfully";
        var errCount = 0;

        var usrn = document.getElementById("usrname1").value;
        var pswd = document.getElementById("pswd1").value;

        errCount += LogInVal(objForm.usrname);
        errCount/*1*/ += LogInVal(objForm.pswd);

        initialize_array();    

        if (errCount != 0)
        {
            alert(errmsg);
            return false;
        }
        else if(authentication(usrn, pswd) == true)

The function authentication() returns true or false, so you don't need to compare it to anything, you can just test the returned value (i.e. there is no need for == true above).

函数authentication()返回true或false,因此不需要将它与任何东西进行比较,只需测试返回的值(即上面不需要= true)。

        {

            alert(msg);
            return true;
            setCookie('invalidUsr',' ttttt');
        }
        else
        {
            alert(errmsg2);
            return false;
        }
    }

Instead of showing alert messages one at a time in an alert, consider putting them in the document adjacent to the elements they relate to. That way the user can see the messaeg while fixing the error.

不要在警报中一次显示一个警报消息,考虑将它们放在与它们相关的元素相邻的文档中。这样用户就可以在修复错误时查看messaeg。

#2


2  

Isn't it cheating to ask us? Your implementation will probably only work in IE, I'd recommend using jQuery as it is impressively powerful at parsing XML.

问我们不是作弊吗?您的实现可能只在IE中工作,我推荐使用jQuery,因为它在解析XML方面非常强大。

I'm not sure why he wants you to write out XML as it's not very intuitive coming from JavaScript. You can do something like this via jQuery

我不知道他为什么要你写XML,因为它不是很直观的来自JavaScript。您可以通过jQuery做类似的事情

//I capture form submitevent

$('form').submit(function( ev ){
  ev.preventDefault(); //I keep form from submitting
  $( xmlDocument ).find('Person').attr({
    username: $("input[name=usrname]),
    password: $("input[name=pswd]),
    //and so on
  });

});

It's up to you on how you 'report' this xml file

这取决于您如何“报告”这个xml文件

#3


0  

Here i am sharing my experience in writing html form data to xml.

在这里,我将分享我编写html表单数据到xml的经验。

  1. Create one html file in one location (D:\\HtmlToXml.html).
  2. 在一个位置创建一个html文件(D:\ HtmlToXml.html)。
  3. And open it with Internet Explorer.
  4. 用ie打开。
  5. Then after provide information and click on submit button, then one file is created in the same directory with name example.xml.
  6. 然后,在提供信息并单击submit按钮之后,在同一个目录中创建一个名为example.xml的文件。
  7. If once an xml is created, then next time onwards on submit button click data will append to same xml file.
  8. 如果创建了xml,那么下次提交按钮时单击data将附加到相同的xml文件。

    <!DOCTYPE html>
    <html>
    <head>

        <title>Display Emp Details</title>

        <script type="text/javascript" language="javascript">

    	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        	var fso = new ActiveXObject("Scripting.FileSystemObject");	
        	var FILENAME='D:\\example.xml';



    function SaveXMLData()
    {
     	validations();
    }


    function createfile()
    {

    	var file;

        	var e1=document.getElementById('empName').value;
        	var p1=document.getElementById('empNumber').value;
        	var em1=document.getElementById('empEmail').value;
        	var d1=document.getElementById('empDate').value;

        	var tablemain = document.getElementById('tblmain');

    	if(fso.fileExists(FILENAME))
        	{
    		xmlDoc.load(FILENAME);
        		var lng;
        		lng=xmlDoc.getElementsByTagName("Details");

        		var xmlread= fso.OpenTextFile(FILENAME,1,true,0);

        		var x=xmlread.readAll();
        		var replace=x.replace('</Emp>','');
        		var sno=lng.length + 1;
        		file=fso.OpenTextFile(FILENAME,2,true);

        		file.writeLine(replace);

        		file.WriteLine('<Details category="'+sno+'">');
        		file.WriteLine('<SNo>'+sno+'</SNo>');
        		file.WriteLine('<Name>'+e1+'</Name>');
        		file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
        		file.WriteLine('<Emailid>'+em1+'</Emailid>');
        		file.WriteLine('<Date>'+d1+'</Date>');

        		file.WriteLine('</Details>');
        		file.WriteLine('</Emp>');
        		
    		alert('another file updated');
        	}
        	else
        	{

        		file= fso.CreateTextFile(FILENAME, true);
        		file.WriteLine('<?xml version="1.0" encoding="utf-8" ?>');
    		file.WriteLine('<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>');
        		file.WriteLine('<Emp>');
        		file.WriteLine('<Details category="1">');
        		file.WriteLine('<SNo>'+1+'</SNo>');
        		file.WriteLine('<Name>'+e1+'</Name>');
        		file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
        		file.WriteLine('<Emailid>'+em1+'</Emailid>');
        		file.WriteLine('<Date>'+d1+'</Date>');

        		file.WriteLine('</Details>');
        		file.WriteLine('</Emp>');     

    		alert('file updated');
        	}

    	<!-- displayData();-->

    	document.getElementById('empName').value='';
    	document.getElementById('empNumber').value='';
    	document.getElementById('empEmail').value='';
    	document.getElementById('empDate').value='';

    addRow('tablemain');
    	file.close();
    }

         
    function validations() 
    {
    	var emp1=document.getElementById('empName').value; 
            var letters = /^[\s A-Za-z]+$/; 
            if(emp1!="")
            {
            	if(emp1.match(letters)) 
              	{
    	    		allnumeric();
              	}
              	else 
    	        {
              		alert('Please input alphabet characters only'); 
              		return false; 
              	}
            }
    	else
    	{
    	  	alert('Please Enter Name.');
     	}
    }

            
    <!--For checking Email-->

    function checkemail()
    {
    	var email = document.getElementById('empEmail');
            var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    	if(email.value!="")
    	{
            	if (!filter.test(email.value)) 
    		{
            		alert('Please provide a valid email address');
            		return false;
            	}
                    else
                    {
                    	DateValidation();
                    }
           	}     
    	else
    	{
    		alert('Please Enter Email.');
    	}
    }


    <!--For checking Date Format-->

    function DateValidation()
    {
        	var date=/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}$/;
        	var empDate=document.getElementById("empDate");

    	if(empDate.value!="")
          	{
    	    	if(empDate.value.match(date))
    	    	{
    	    		createfile();
    	    	}
    	    	else
    		{
        	     		alert("Please provide valid date : DD-MM-YY(YYYY)");
    			return(false);
    	    	}
          	}
    	else
    	{
    		alert('Please Enter Date.');
    	}
    }


    <!--For checking phone number-->

    function allnumeric() 
    {
    	var numbers=/^\d{10}$/;
        	var empNumber=document.getElementById("empNumber");
    	if(empNumber.value!="")
    	{
    		if(empNumber.value.length=="10")
    		{
        			if(empNumber.value.match(numbers))
        			{
           				checkemail();
        			}
        			else
    			{
    	    			alert("Phone number should be numeric");
        				return(false);
    			}
    		}
    		else
    		{
    			alert('Phone Number should be like: 9876543210');
    		}
    	}
    	else
    	{
    		alert('Please Enter Phone Number.');
    	}
    }



    function addRow(id) 
    {

        if(fso.fileExists(FILENAME))
        {

    	xmlDoc.load(FILENAME);
        	var x;
        	x=xmlDoc.getElementsByTagName("Details");

            var table = document.getElementById('tbl');        



    	var nxtbtn= document.getElementById("btnnext");
    	var prvbtn=document.getElementById("btnprev");
    	nxtbtn.disabled=true;
    	prvbtn.disabled=true;
    	if(x.length >5)
    	{
    		nxtbtn.disabled=false;
    	}
    	var j=0;k=5;
    	if(k>x.length)
    	{k=x.length;}

    	var store=document.getElementById("txtstore");
    	var maxval=document.getElementById("txtmax");

    	if(id=="btnprev")
    	{        
    		if((store.value % k)==0)
    		{
    			store.value = store.value - k ;
    			if(store.value>0)
    			{
    				j = parseInt(store.value);
    				k += parseInt(store.value);
    			}
    		}
    		else
    		{
    			store.value =store.value - (store.value % k) ;

    			if(store.value >0)
    			{
    				j = store.value - k;
    				k = store.value;
    			}
    	
    		}
    	
    		if(j > 0)
    		{
    			prvbtn.disabled=false;
    		}

    	}
    	if(id=="btnnext")
    	{
    		if(store.value==0)
    		{
    			store.value=table.rows.length;
    		}
    		else if(store.value <0)
    		{
    			store.value=maxval.value;
    		}
    		prvbtn.disabled=false;
    	    	if(store.value >=k)
    		{
    			j +=parseInt(store.value);
    			k +=parseInt(store.value);
    			if(k >= x.length)
    			{
    				k=x.length;
    				nxtbtn.disabled = true;
    				prvbtn.disabled = false;
    			}
    		}
    	}

    	table.innerHTML = "";
    	var rowCount = 0;

         	for (i=j;i<k;i++)
    	{
         
            	var row = table.insertRow(rowCount);

    	        var cell1 = row.insertCell(0);
            	var element1 = document.createElement("input");
    	        element1.type = "checkbox";
    	        element1.id =  "id2" ;
            	cell1.appendChild(element1);

    	        // Create label
            	var label = document.createElement("label");
    	        label.htmlFor =  "id2" ;
            	cell1.appendChild(label);

    	        var cell2 = row.insertCell(1);
            	cell2.innerHTML = x[i].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;

    	        var name = row.insertCell(2);
            	var elname =document.createElement("input");
    	        elname.type = "text";
    		elname.readOnly=true;
    		elname.value=x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
    	        name.appendChild(elname);

    	        var phnno = row.insertCell(3);
            	var elphn =document.createElement("input");
    	        elphn.type = "text";
    		elphn.readOnly=true;
    		elphn.value=x[i].getElementsByTagName("PhoneNumber")[0].childNodes[0].nodeValue;
            	phnno.appendChild(elphn);

    	        var email = row.insertCell(4);
            	var elemail =document.createElement("input");
    	        elemail.type = "text";
    		elemail.readOnly=true;
    		elemail.value=x[i].getElementsByTagName("Emailid")[0].childNodes[0].nodeValue;
            	email.appendChild(elemail);

    	        var date = row.insertCell(5);
            	var eldate =document.createElement("input");
    	        eldate.type = "text";
    		eldate.readOnly=true;
    		eldate.value=x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue;
            	date.appendChild(eldate);
    	
    		rowCount +=1;
         	}
    	maxval.value=x[table.rows.length - 1].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;

    	if(id=="btnprev")
    	{
    	 store.value =store.value - 5;
    	}
    	 else
    	{
        	 store.value =parseInt(k);
    	}
       }
    }

        </script>
    </head>

    <body onload="addRow('tbl')">

    	<form id="empForm" action="" method="get">

        	<p><b>Emp Registration:</b></p>

        	<table>
        		<tr>
        			<td>Name:</td>
        			<td><input type="text" id="empName" maxlength="25"/></td>
        		</tr>
        		<tr>
        			<td>Phone Number:</td>
        			<td><input type="text" id="empNumber" maxlength="10"/></td>
        		</tr>
    	    	<tr>
        			<td>EmailId:</td>
        			<td><input type="text" id="empEmail"/></td>
        		</tr>
        		<tr>
        			<td>Date:</td>
        			<td><input type="text" id="empDate" maxlength="10"/></td>
        		</tr>
        		<tr>
        			<td align="center">
    			<input type="button" value="Submit" onclick="SaveXMLData()"/></td>
        			<td>
    			<input type="button" value="Show Data" id="show" onclick="displayData(this.id)" style="display:none;"/></td>
        		</tr>
        	</table>
    	<!-- <table><tr><td><input type="button" onclick="displayData(this.id)" value="Prev" id="prev" disabled="disabled"></td>
    	   <td><input type="button" onclick="displayData(this.id)" value="Next" id="next" disabled="disabled"></td></tr></table> -->

     	<div id='displaydatadiv'>	
        	</div>
    	<!-- <INPUT type="button" value="Add Row" onclick="addRow('tbl')" /> -->
    	
    	<div style="height: 135px; width:650px; background-color: Lavender;" >
    		<TABLE id="tbl" width="350px">    
      		</TABLE>
    	</div>
    	<table id="tblmain" border="1" style="display:true" ></table>
    		<input type="button" id="btnprev" value="Prev" onclick="addRow(this.id)" disabled="disabled">
    		<input type="button" id="btnnext" value="Next" onclick="addRow(this.id)" disabled="disabled">

    		<input type="hidden" id="txtstore" style="display:none;">
    		<input type="hidden" id="txtmax" style="display:none;">

    </body>
    </html>