What's wrong with this? .serialize() returns nothing. I've tried several ways to do this, but all end up with empty dictionary. form, input, #idofform, #idofinput, nothing happens...
$(document).ready(function(){
$.post("/resultjs/", $("form").serialize(), function(data) {
$('.content').html(data);
});
});
...and html. just a normal simple form. To be completely clear: I would like collect post data from the form, post them to /resultjs/ (django), retrieve the result and write it to .content div
<div id="search">
<form action="/resultjsall/" method="post"><div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='somedjangocsrftoken开发者_JS百科' /></div>
<input type="text" name="what" id="what" value="" size="80" />
<input type="submit" value="Find" />
</form>
</div>
Send your $.post
only upon submitting the function (hence the event handler <form_selector>.submit( ... )
, see .submit()
.
Notice that I kept the $(document).ready
part. The purpose of that is to wait for all other scripts and the DOM to load before doing stuff such as binding events to elements in the DOM (such as that form), because if the elements you're binding to aren't loaded at the time the binding executes, nothing will happen instead.
$(document).ready(function() {
$("form#myForm").submit(function() {
$.post($(this).attr("action"), $(this).serialize(),
function(data) {
if (data == "") { alert("No data returned!"); return; }
// otherwise set the content div to the data we received
$('div.content').html(data);
}
);
// disable normal submitting of the form since we use ajax now
return false;
});
});
You need to bind your form submission to the clicking of the submit button. Do something like this instead:
$(document).ready(function() {
$("form input[type='submit']").click(function() {
$.post($("form").attr("action"), $("form").serialize(), function(data) {
$('.content').html(data);
});
return false;
});
});
精彩评论