让用户上传一个xml文件并对其进行解析(不使用PHP)


Let user upload an xml file and parse it (without PHP)?

我对CSS(3)和HTML(5)非常熟悉,但我目前的项目让我可以更进一步。然而,这对我来说是完全未知的。在我的项目中,我有一个文本区域,用户可以在其中提交一些XML,然后我用jQuery的$.parseXML方法解析这些XML。但是,我想添加上传XML文件的功能。

我想上传按钮应该是这样的:

<form name="upload-form" action="???" method="???">
    <input type="file" name="upload-field">
</form>

然而,我不知道行动和方法应该是什么样子。因为我停留在同一页上,不应该发生任何壮观的事情,我猜动作属性可以省略吗?方法属性可能是get,而不是post(1)

然后呢我不知道如何在jQuery的解析器中从上传的XML文档中获取数据(2)此外,如何检查正确的文件类型?这是否会在服务器端发生(3)

action包含将接收表单数据的服务器端脚本的名称。使用post时,浏览器不会将输入字段的内容解析为url。服务器端脚本(例如php中的脚本)将接收请求、进行安全检查并保存数据。

<form name="upload-form" action="serversidescript.php" method="post">
  <input type="file" name="upload-field">
  <input type="submit" value="Submit">
</form>

serversidesccript.php

<pre>
<?php
print_r($_REQUEST); // shows the array containing the form data

将方法留空,然后使用post方法。对文件使用post很重要,因为它具有安全功能,可以上传更多数据。

由于它正在上传一个文件,您需要添加enctype,enctype="multipart/form-data",否则它将无法工作

<form name="upload-form" action="" method="post" enctype="multipart/form-data" >
    <input type="file" name="upload-field">
    <input type="submit" value="Submit">
</form>

然后,为了解析文件,您需要使用jquery读取xml文件,然后根据需要编写一个解析器函数。

//write the custome parse function
function parse(data){
   //code for your parse function goes here.
   // to append the file to html, I need the actual structure of the file to show you
}
//this reads the xml file using jquery
$.ajax({
    url: 'name.xml', // name of file you want to parse
    dataType: "xml",
    success: parse, //this calls the parse function
        error: function(){alert("Error: Something went wrong");}
  });