weixin_33698823 2016-08-09 20:37 采纳率: 0%
浏览 80

使用Ajax的NodeJS + Express

I am writing a web utility that submits a file and some form fields via Ajax. There's a part of my form that is dynamic, as in it can have multiple rows for the same value. The user can add as many rows as they like. The form also takes in a file.

The HTML ends up being something to the effect of:

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

Upon the submit button being clicked, the following Ajax is called:

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

Here's the issue. I'm now stuck in a sort of catch-22. The recommended way to pass files through Ajax is using the FormData object. The problem is that I cannot get FormData to cooperate with my arrays. When the NodeJS server receives the Ajax submission as FormData object, it doesn't play nicely with the form arrays. It treats them as individual input fields like (console.log(request.body)):

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

where as the .serialize() method gives me a nice array like:

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

but .serialize() does not work with file submissions.

So, I'm wondering what the best way to support this. My requirements are that the form cannot leave the page upon submit, so I felt Ajax was the right way to go.

Is there any way for FormData to play nicely with input arrays and NodeJS Express? Or any sort of work around for this? I'd really rather not have to do some sort of string finagling when .serialize() does it so nicely.

  • 写回答

2条回答 默认 最新

  • weixin_33726313 2016-08-09 23:35
    关注

    Perhaps not the answer you are looking for but I think it might solve your issue:

    Simply change the object that you recieve on the server:

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

    To what you want (mainForm being the name of the object sent from the client):

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

    The array inputField now contains the values in the correct format (console.log(inputField)):

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

    Fiddle: https://jsfiddle.net/00ocdujy/3/

    评论

报告相同问题?