表单标签和AJAX请求

I made a simple page with a couple of radio buttons and a textfield as an exercise:

<html>
   ...

    Student list: <input type="radio"   name="list" value="students">
    Lession list: <input type="radio"   name="list" value="lessons">

    <h2>Type the course code:</h2> 

    Code: <input type="text" name="code" id="code">
   <input type="submit" id="submit">
</html>

And I added a listener to the button through Javascript.

Now via Javascript I collect the data from the various input fields, and pack them in a request:

function prepareRequest(req) {
    var radios = document.getElementsByName("list");
    var value;
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {            
            value = radios[i].value;
        }
    }
    var code = document.getElementById("code").value;
    var url = "../AjaxServlet?value="+value+"&code="+code;
    req.open("GET", url, true);
    req.send();
}

I call my servlet through Javascript, GET my data, and then handle the response.

If I wanted to do this with "pure" HTML, I'd enclose those inputs in a FORM tag, like this:

<form action="../AjaxServlet" method="get">
    ...
   <input type="submit" id="submit">
</form>

Now when I hit submit, the servlet is called "through" the form, which sends all the data it collected automatically. Of course this is synchronous and the page has to reload/redirect.

What I'm wondering is, with AJAX, is there any need for the form tag? What I did seemed intuitive enough, get the input elements from the DOM, extract the data and then pack them in a request manually. Is this right or wrong? Is there a standard or better way to do this?

查看全部
weixin_33739523
weixin_33739523
2016/09/30 17:10
  • html
  • ajax
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信

1个回复