MDN may have intermittent access issues April 18 13:00 - April 19 01:00 UTC. See whistlepig.mozilla.org for all notifications.

mozilla
Los resultados de tu búsqueda

    Usando Objetos FormData

    Los objetos FormData le permiten compilar un conjunto de pares clave/valor para enviar mediante XMLHttpRequest. Está destinado principalmente para el envío de los datos del formulario, pero se puede utilizar de forma independiente de las formas con el fin de transmitir los datos tecleados. Los datos transmitidos están en el mismo formato que usa el método submit()del formulario para enviar los datos si el tipo de codificación del formulario se establece en "multipart/form-data".

    Creación de un objeto FormData desde cero

    Usted mismo puede construir un objeto FormData, instantiating it then appending fields to it by calling its append() method, like this:

    var formData = new FormData();
    
    formData.append("username", "Groucho");
    formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
    
    // HTML file input user's choice...
    formData.append("userfile", fileInputElement.files[0]);
    
    // JavaScript file-like object...
    var content = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
    var blob = new Blob([content], { type: "text/xml"});
    
    formData.append("webmasterfile", blob);
    
    var request = new XMLHttpRequest();
    request.open("POST", "http://foo.com/submitform.php");
    request.send(formData);
    
    Nota: The fields "userfile" and "webmasterfile" contain both a file. The number assigned to the field "accountnum" is immediately converted into a string by the FormData.append() method (the field's value can be a Blob, File, or a string: if the value is neither a Blob nor a File, the value is converted to a string).

    This example builds a FormData instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the XMLHttpRequest method send() to send the form's data. The field "webmasterfile" is a Blob. A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. In order to build a Blob you can invoke the Blob constructor.

    Recuperando un objeto FormData de un formulario HTML 

    To construct a FormData object that contains the data from an existing <form>, specify that form element when creating the FormData object:

    var formData = new FormData(someFormElement);
    

    Por ejemplo:

    var formElement = document.getElementById("myFormElement");
    var request = new XMLHttpRequest();
    request.open("POST", "submitform.php");
    request.send(new FormData(formElement));
    

    You can also append additional data to the FormData object between retrieving it from a form and sending it, like this:

    var formElement = document.getElementById("myFormElement");
    formData = new FormData(formElement);
    formData.append("serialnumber", serialNumber++);
    request.send(formData);

    This lets you augment the form's data before sending it along, to include additional information that's not necessarily user editable on the form.

    Enviando archivos usando objetos FormData

    You can also send files using FormData. Simply include an <input> element of type "file":

    <form enctype="multipart/form-data" method="post" name="fileinfo">
      <label>Your email address:</label>
      <input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /><br />
      <label>Custom file label:</label>
      <input type="text" name="filelabel" size="12" maxlength="32" /><br />
      <label>File to stash:</label>
      <input type="file" name="file" required />
      <input type="submit" value="Stash the file!" />
    </form>
    <div id="output"></div>
    

    Then you can send it using code like the following:

    var form = document.forms.namedItem("fileinfo");
    form.addEventListener('submit', function(ev) {
    
      var
        oOutput = document.getElementById("output"),
        oData = new FormData(document.forms.namedItem("fileinfo"));
    
      oData.append("CustomField", "This is some extra data");
    
      var oReq = new XMLHttpRequest();
      oReq.open("POST", "stash.php", true);
      oReq.onload = function(oEvent) {
        if (oReq.status == 200) {
          oOutput.innerHTML = "Uploaded!";
        } else {
          oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
        }
      };
    
      oReq.send(oData);
      ev.preventDefault();
    }, false);
    

    Nota: If you pass in a reference to the form the method specified in the form will be used over the method specified in the open() call.

    Nota: This example is directing the output to a Perl CGI script running on the server, and handles HTTP errors, although not prettily.

    You can also append a File or Blob directly to the FormData object, like this:

    data.append("myfile", myBlob, "filename.txt");
    

    When using the append method it is possible to use the third optional parameter to pass a filename inside the Content-Disposition header; that is send to the server. When no filename is specified (or the parameter isn't supported), the name "blob" is used.

    You can also use FormData with jQuery if you set the right options:

    var fd = new FormData(document.getElementById("fileinfo"));
    fd.append("CustomField", "This is some extra data");
    $.ajax({
      url: "stash.php",
      type: "POST",
      data: fd,
      processData: false,  // tell jQuery not to process the data
      contentType: false   // tell jQuery not to set contentType
    });
    

    Envío de formularios y carga de archivos vía AJAX  sin  objetos FormData

    Si usted quiere saber cómo serializar y enviar vía AJAX un formulario sin utilizar objetos FormData, por favor leer este párrafo .

    Vea también

    Etiquetas y colaboradores del documento

    Contributors to this page: wilo
    Última actualización por: wilo,