I was wondering if I need to use the form element in my HTML when I make an Ajax call. Can I just get away with using, for instance, the input element, and then specifying the rest of the information (URL, etc.) in the JavaScript?
By "need," I mean to say is there some stylistic, security or reliability reason to continue using the <form>
element?
I was wondering if I need to use the form element in my HTML when I make an Ajax call. Can I just get away with using, for instance, the input element, and then specifying the rest of the information (URL, etc.) in the JavaScript?
By "need," I mean to say is there some stylistic, security or reliability reason to continue using the <form>
element?
- thanks everyone, appreciate the responses. – worker1138 Commented Oct 12, 2011 at 20:26
4 Answers
Reset to default 6If you're doing an AJAX request, you do not technically need the <form>
tag. However, there are some reasons why you might want to keep using it
- It may be more semantically correct for your situation (e.g. the user actually is submitting a "form").
- Imagine if a user does not have JavaScript enabled or are using a browser that does not support JavaScript. Your site may be able to degrade more gracefully. That is, the user can still submit the form even without JavaScript.
- There are some JQuery plugins that can parse a
<form>
and submit it with AJAX rather than requiring you to select each<input>
element, extract its value, and construct the AJAX request yourself.
You don't need a form, no. If you have a lot of elements, it's obviously good to wrap them in a div
to make selecting the inputs easier.
There is an advantage to using a form
, however, which is graceful degradation. If you have a form
with a normal submit
button with the following jQuery:
$("form").submit(function(e) {
e.preventDefault();
// Ajax request
});
The e.preventDefault()
will stop the form from submitting normally, and do the AJAX request you write below. If the user doesn't have JS enabled, the form will submit using the usual method without JS.
No you don't explicitly need it unless you need specific form method/action stuff. You can directly use input
fields and have a button with a click event bound to it and call it via ajax/jquery.
I personally use the form-based technique if I want to show a totally different page/representation after the user 'submits' the form.
There is no stylistic, security or reliability reason to using (or not using) a form. You could specify the same parameters in the $.ajax()
if you want.
It's how you want to design the application...
If you use ajax, you do not need to make a form. If you use normal form method, you need one
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744439141a4574261.html
评论列表(0条)