How to implement Django Form using Minimal jQuery Ajax [ Level of question - Intermediate ]
If you were to replace the code marked [from here - till here] with som开发者_开发问答ething minimalistic what would it be?
$('#post_form').submit(function(event){
event.preventDefault();
var data = {}
// From here
data.k = $('#k').val(); //'k' would be the id of some input field
data.j = $('#j').val(); //and so on for 'l', 'm' , 'n' etc. you get it
.......
// Till here
$.post("/ajax/post_test/",
data,
function(responseData) {
// handle the response
},
"json"
);
});
It would be awesome if this 'data' object could be directly used in Django as a form and hence be able to leverage Django's inbuilt validation system.
The ideal answer would look something like this -
data = $('#post_form').DumpData()
And if anybody feeling really kind today could you also please tell me how i can handle the response as well? I would be really really grateful. Thank you guys.
P.S. Save my soul.
You are looking for the serialize
method:
The .serialize() method creates a text string in standard URL-encoded notation. It operates on a jQuery object representing a set of form elements.
So it doesn't give you an object, but it works as the data parameter for a jQuery AJAX call.
If you really want them as an object, there's serializeArray
, which isn't exactly there as it is an array of objects with names and values, but you could then turn it into a one-level object.
精彩评论