So, you're basically asking how to get JSON data by a POST request?
Instead of
$.getJSON('servleturl', function(data) {
alert(data);
});
use
$.post('servleturl', function(data) {
alert(data);
});
When you let the servlet do response.setContentType("application/json")
, then the data
is already in JSON format.
However, after reading your question and the comments once more, I think you're basically asking how to submit a POST form using jQuery. This has essentially nothing to do with JSON (although the servlet can return a JSON response if desired).
Assuming the following form
<form id="formid" action="servleturl" method="post">
<input type="text" name="foo" />
<input type="text" name="bar" />
<input type="submit" />
</form>
here's how you can "ajaxify" it (do it during document ready!)
$('#formid').submit(function() {
$form = $(this);
$.post($form.attr('action'), $form.serialize(), function(data) {
// Do something with response. Display message? Redirect to other page?
alert(data);
});
});
For another example also see this answer.
There exist plugins which do it more nicely, such as jQuery Form. It's then as simple as
$('#formid').ajaxForm(function(data) {
// Do something with response. Display message? Redirect to other page?
alert(data);
});
and it also supports <input type="file">
elements without much trouble.