Answer the question
In order to leave comments, you need to log in
How to clear JSON data received by .serializeArray() method?
Hello!
There is a problem of the following content.
I have an html form. There is this code:
$( "form" ).submit(function( event ) {
console.log(JSON.stringify($(this).serializeArray()));
var arr = $( "form" ).serializeArray();
$.ajax({
type: "POST",
url: "make_order",
// Tut pizdos
data: JSON.stringify(arr),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(test);},
failure: function(errMsg) {
alert(errMsg);
}
});
event.preventDefault();
});
[{"name":"assigment","value":"1"},{"name":"subject","value":""},{"name":"title","value":""},{"name":"description","value":""},{"name":"`pages","value":""},{"name":"sources`","value":""},{"name":"id_writer","value":""},{"name":"discount_code`","value":""},{"name":"email","value":""}]
Answer the question
In order to leave comments, you need to log in
/*
data - полученный ответ от сервера
*/
var result = [];
for (var i = 0; i < data.length; i++) {
var obj = {};
obj[data[i].name] = data[i].value;
result.push(obj);
}
console.log(result);
// результат
/* [{"assigment":"1"},{"subject":""},{"title":""},{"description":""},{"`pages":""},{"sources`":""},{"id_writer":""},{"discount_code`":""},{"email":""}] */
You can add your method to jQuery and safely use it later:
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question