带有Ajax的NodeJS + Express

我正在编写一个Web实用程序,通过Ajax提交一个文件和一些表单域。 我的表单中有一部分是dynamic的,因为它可以有多个相同的值。 用户可以添加任意数量的行。 该表格还包含一个文件。

HTML最终会导致以下效果:

<form id="main-form"> <input name="inputField[0]" type="text"></input> <input name="inputField[1]" type="text"></input> <input name="inputField[2]" type="text"></input> <input name="inputField[3]" type="text"></input> .... <input name="inputField[i]" type="text"></input> <input type = "file" name="file></input> </form> 

点击提交button后,会调用以下Ajax:

 var mainForm = $("#main-form"); $.ajax({ url: '/', type: 'POST', success: successHandler, data: mainForm.serialize(), complete: checkError, cache: false, processData: false }); 

这是问题。 我现在陷入了一种困境 – 22。 通过Ajax传递文件的推荐方法是使用FormData对象。 问题是我不能让FormData与我的数组合作。 当NodeJS服务器接收Ajax提交作为FormData对象时,它不能很好地与表单数组一起玩。 它将它们视为单独的input字段,例如(console.log(request.body)):

 { normalField: 'normalResult', 'inputField[0]': 'test0', 'inputField[1]': 'test1', 'inputField[2]': 'test2', 'inputField[3]': 'test3', } 

在那里.serialize()方法给了我一个很好的数组,如:

 { normalField: 'normalResult', inputField: [ 'test1', 'test2', 'test3', 'test4' ] } 

但.serialize()不适用于文件提交。

所以,我想知道什么是支持这个最好的方法。 我的要求是,表单不能离开页面提交,所以我觉得阿贾克斯是正确的路要走。

有没有什么办法让FormData和input数组和NodeJS Express一起玩呢? 或者任何forms的解决这个? 当.serialize()很好地完成时,我真的宁愿不做某种types的string拼凑。

也许不是你正在寻找的答案,但我认为这可能会解决你的问题:

只需更改您在服务器上收到的对象:

 { 'inputField[0]': 'test0', 'inputField[1]': 'test1', 'inputField[2]': 'test2', 'inputField[3]': 'test3', } 

你想要什么(mainForm是从客户端发送的对象的名称):

 var inputField = []; for (var val in mainForm) { inputField.push(mainForm[val]); } 

数组inputField现在包含正确格式的值(console.log(inputField)):

 ['test0', 'test1', 'test2', 'test3']; 

小提琴: https : //jsfiddle.net/00ocdujy/3/

它看起来像你使用jQuery ,所以我build议使用下面的插件:

http://jquery.malsup.com/form/

  1. 简单包括它:

    • <script src="http://malsup.github.com/jquery.form.js"></script>
  2. 使用以下方法:

    • $('#main-form').ajaxForm(function() {

检查链接的更多细节