¿Cómo agregar datos a un formulario cuando se envía a través de una solicitud POST AJAX? [duplicar]
Frecuentes
Visto 8,662 equipos
5
Estoy usando jQuery's $.ajax()
function to submit a form. I pass the form data like this:
data: form.serialize()
However, I would like to add additional data to the POST request.
Según esta respuesta, the way to do this is to use serializeArray()
on the form, then push data onto the resulting array of objects. The problem is that when I then try to serialize the resulting array, jQuery returns an error.
Aquí hay un ejemplo:
<form id="test">
<input type="hidden" name="firstName" value="John">
<input type="hidden" name="lastName" value="Doe">
</form>
JS:
console.log($("#test").serialize()); // firstName=John&lastName=Doe
var data = $("#test").serializeArray();
console.log(data); // [Object, Object]
data.push({name: 'middleName', value: 'Bob'});
console.log(data); // [Object, Object, Object]
console.log(data.serialize()); // Uncaught TypeError: undefined is not a function
¿Qué estoy haciendo mal?
3 Respuestas
7
As pointed out by kapa, jQuery permits you to pass the array you get from serializeArray()
directamente como un data
parameter, so your code can be as simple as;
var data = $("#test").serializeArray();
data.push({name: 'middleName', value: 'Bob'});
jQuery.ajax({
data: data,
// Other params
});
However, to explain why your previous code wasn't working (and here starts my previous answer); serializeArray()
literally returns an array. Array's don't have a serialize()
method on them; which is why your code was failing.
En lugar de usar serialize()
on the array returned from serializeArray()
, llamada jQuery.param()
;
var data = $("#test").serializeArray();
data.push({name: 'middleName', value: 'Bob'});
console.log(jQuery.param(data));
jQuery.param()
is specifically provided to convert the { name, value }
pairs generated by serializeArray()
into a query string.
contestado el 28 de mayo de 14 a las 13:05
1
serialize
is a jquery method used to serialize a form object. Once you call serialize
, you no longer have a jquery object, and thus you cannot serialize it. You should be able to pass your JSON object to $.ajax
by stringifying it with the JSON object:
$.ajax({
data: JSON.stringify(data)
//...
});
contestado el 28 de mayo de 14 a las 13:05
0
In addition to the other answer, sometimes it is easier to simply add hidden input elements, before the serilazation.
$('<input type=hidden>').attr({name:'middleName',value:'bob'}).appendTo('form#test')
contestado el 28 de mayo de 14 a las 13:05
This should be a comment and not an answer since it doesn't answer the question. - afaolek
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript jquery ajax forms or haz tu propia pregunta.
Why are you trying to call
serialize
on it? Simply follow the example code in the linked answer. Usedata
in your AJAX call, it is ready. Likedata: data
. - kapaDid you try to use data in your ajax call after
.push()
; you shouldn't try to serialize the array. - PeterKA@kapa the examples I've found for
$.ajax()
show the data as being passed asform.serialize()
, which puts the inputs into a string (like a GET request would). That's why I'm trying to callserialize()
on the array, to convert it to a string. - NateYou may also use JSON jsfiddle.net/hqj4E/1 - Nico O
@Nate Just read the docs instead of following examples blindly. Or follow examples blindly, and simply copy it from the answer in the linked question. Both methods will work in this case :). - kapa