如何使用Javascript将HTML中的Form数据写入XML [英] How to write data from Form in HTML to XML with Javascript

查看:90
本文介绍了如何使用Javascript将HTML中的Form数据写入XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我班的作业。我需要做的是创建一个注册页面。当用户按下提交按钮时,我已将表单上的所有信息写入使用Javascript的现有XML文件。这是在客户端完成的,只能通过HTML,Javascript和XML。顺便说一下,我的教授故意没有教我们如何做到这一点,因为他希望我们自己研究它。另外,我不太熟悉Javascript,尤其是内置函数,如果可能的话,请解释代码的每一行或每个方法正在做什么。



让我开始,这里是我现有的XML的样子:

 <?xml version =1.0encoding =utf-8? > 
<! - GGFGFGFVBFVVVHVBV - >
< PersonInfo>
< Person Usrname =Bob111Pswd =Smith111personid =111FirstName =BobLastName =SmithDOB =01/01/1960Gender =MTitle =Hello1 >
< / Person>
<! - 几行< person>这里 - >
< / PersonInfo>

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



基本上,据我所知,一旦按下提交,我就必须从注册页面创建XML行Person。然后将其推送到已有我的XML信息的数组,然后使用数组上的信息覆盖我的XML文档。我的问题是,我完全不知道该怎么做。



对于那些想要知道我的注册页面的样子,请点击这里:

 < html> 

< head>
< title>注册< /标题>
< link rel =stylesheettype =text / csshref =CSS_LABs.css/>
< / head>


< body>

< div class =form>
< form id =Registrationaction =method =get>

用户名:< input type =textname =usrnamemaxlength =10/> <峰; br />
密码:< input type =passwordname =pswdmaxlength =20/> <峰; br />

< hr>

PersonID:< input type =textname =PID/> <峰; br>

< hr>

名字:< input type =textname =fname/> <峰; br>
姓氏:< input type =textname =lname/>

< hr>

DOB:< input type =textname =dob/> <峰; br>

< hr>

性别:< input type =textname =sex/> <峰; br>

< hr>

标题:< input type =textname =title/> <峰; br>

< hr>

秘密问题:< br>
< select name =secret?>
< / select> <峰; br>

答案:< input type =textname =answer/> <峰; br> <峰; br>

< input type =submitvalue =submit/>
< / form>
< / div>

< / body>

< / html>

顺便说一下,我知道我的HTML文档中的某些信息可能没有适当的措辞,所以希望你们不介意。另外,稍后我会在稍后将答案提交给秘密问题,以后再修正我的XML。



好吧,非常感谢大家。

更新!!!



在这里,我终于想出了如何用Javascript创建XML文档,代码如下:

  var xmlDoc = new ActiveXObject(Microsoft.XMLDOM); 
var fso = new ActiveXObject(Scripting.FileSystemObject);
var FILENAME ='G:\\CST2309 - 网络编程1 \\复制Take Home Exam - Copy\\\\ersonXML2.xml';

函数SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME,true);
file.WriteLine('<?xml version =1.0encoding =utf-8?> \\\
');
file.WriteLine('< PersonInfo> \\\
'); (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> \\\
');
} // end for countr

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

} //结束SaveXML函数--------------------

函数LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //结束函数LoadXML()

函数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);
} //结束函数initialize_array()

这里的代码是做什么的,它将我原来的XML文件加载到一个数组中,以便它可以创建一个新的XML文件。基本上我创建了XML文件部分,但仍需要帮助其余的东西。



我的目标是试图获取我的表单数据并将其推送到我现有的数组中,而不是覆盖它,添加到它,以便我可以使用新的注册信息。这是我绝对不知道该怎么做的地方。一些指针会很好。

解决方案


顺便说一下,我的教授故意没有教我们如何要做到这一点,因为他希望我们自己研究它。


这应该给你一个关于更深入搜索的暗示。无论如何,我不打算评论每一行,但我会提供一些提示。

  var xmlDoc = new ActiveXObject(Microsoft.XMLDOM); 

这是Microsoft创建XML文档的专有方式,通常包含在try..catch因为在不同版本的IE中提供了不同的ActiveXObjects。您还需要查找 document.implementation.createDocument

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

您可能想要查看async参数。

  xmlObj = xmlDoc.documentElement; 
}

// declare&初始化数组
var arrPerson = new Array();

使用数组文字被认为是更好的做法: ... = [];

  //初始化数组w / xml 
函数initialize_array()
{
LoadXML(PersonXML.xml);
var x = 0;
while(x

获取 xmlObj.childNodes 在每个循环中效率低下,请考虑存储长度并与该值进行比较。

  {
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( 标题));

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


您可以直接将值分配给 arrPerson 并去掉 tmpArr

  x ++; 

使用plain for循环会为您增加x。



$验证
函数LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background =red;
返回1;
}

else
{
objtxt.style.background =white;
返回0;


并非所有的浏览器都会让你设计背景颜色输入元素。

  //主验证
函数MainVal(objForm)
{
var errmsg =空字段;
var errmsg2 =不正确的用户名和密码;

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

  var msg =您已成功登录; 
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);
返回false;

else if(authentication(usrn,pswd)== true)

函数 authentication()返回true或false,所以你不需要将它与任何东西进行比较,你可以测试返回的值(即没有必要 == true 以上)。

  {

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


$ / code $ / pre

不是每次只显示一个警报消息警惕性,请考虑将它们放置在与其相关元素相邻的文档中。这样用户可以在修复错误时看到messaeg。


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.

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

    <?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.

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.

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.

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:

    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.

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.

解决方案

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.

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

You might want to check out the async parameter.

     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.

    {
        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.

        arrPerson.push(tmpArr);

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

        x++;   

Using a plain for loop will increment x for you.

    }
    }

    //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).

        {

            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.

这篇关于如何使用Javascript将HTML中的Form数据写入XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆