With JavaScript and AJAX, do I still need the HTML <form> tag and do I still need to submit forms to the server using a "submit" button?
Back when I learned HTML, CGI was king, and the proper way to interact with the server was to put <input>
tags inside of a <form>
tag. When the user pressed the "submit" button, either an HTTP GET or an HT开发者_运维知识库TP POST message was sent to the server and the browser refreshed using the HTML code returned from the CGI program on the server.
Now I've started doing web stuff again and I've been learning JavaScript and jQuery. Since jQuery can intercept events like click
, keypress
, and focusout
, and can read data with $.ajax()
and $.getJSON()
, is there still a need to have a <form>
tag at all?
Maybe "real forms" are still necessary if I want to support users that have JavaScript turned off?
Forms can still help you, but the short answer is no, not really.
If you have a group of inputs that are going to pertain to a certain AJAX request, then it might be easier to keep them in their own form for validation/serialization purposes. For example:
$.ajax({
url: 'ajax/test.html',
dataType: 'json',
method: 'POST',
content: $('form#login_form').serialize(), // <-- Serialize elements only in
success: function(data) { // the login_form container.
$('.result').html(data);
}
});
Depending on your requirements, you may need to keep your forms around for nice degradation for users who have Javascript turned off. You're still going to need to submit the forms, so having the form set up and in place is a good idea.
If you're using ajax, as long as you don't have any direct posts or gets, a form tag is not required. However, it is still good html design.
You can do both, submit or not. It can depend on which form element you want to listen to for changes. But you can do something like this as just one example:
<SELECT NAME="tree" onchange="doSomething( someVar );">
But again, it depends on which element of the page you want to manipulate.
精彩评论