问题
I read some AJAX-Form tutorial like this. The tag form is used in HTML code. However, I believed that it is not necessary. Since we send HTTP request through XmlHttpRequest, the sent data can be anything, not necessary input in form.
So, is there any reason to have form tag in HTML for AJAX application?
回答1:
Apart from progressive enhancement as already discussed (don't make your site require JavaScript until it really has to), a <form>
with onsubmit
would be necessary to reliably catch an Enter keypress submission.
(Sure, you can try trapping keypresses on separate form fields, but it's fiddly, fragile and will never 100% reproduce the browser's native behaviour over what constitutes a form submission.)
回答2:
Sometimes, web apps using ajax to transform their data either use forms as a fallback when the user has no JavaScript enabled (a sometimes expensive but very good thing to do).
Otherwise, if an application builds and sends an AJAX request, there is no compelling reason to use a form
except in rare special cases when you actually need a form element. Off the top of my head:
- when using jQuery's form serialize function
- when monitoring all fields in a form for changes
- when there is need to make use of the
reset form
button (that to my knowledge is available in a proper<form>
only).
回答3:
I see at least two possible reasons :
- Graceful degradation (see also Unobtrusive JavaScript) : if a user doesn't have Javascript enabled in his browser, your website should still work, with plain-old HTML.
- Behavior of the browser : users know what forms look like and how they behave (auto-completion, error-correction, ...) ; it's best not going too far away from that
And I would add that, if you want the user to input some data, that's why <form>
and <input>
tags exist ;-)
Using the right tags also helps users -- as an example, think about blind users who are navigating with some specific software : those software will probably have a specific behavior for forms an input fields.
回答4:
It really depends what you're doing. If you're wanting to take form content submitted by the user and use AJAX to send that somewhere then you're going to want to use the form tag so your user can enter their data somewhere.
There will be other times when you're not sending data from a form and in that case, you wont have a form to be concerned about :)
来源:https://stackoverflow.com/questions/2704753/is-form-tag-necessary-in-ajax-web-application