weixin_33739523 2016-09-30 17:10 采纳率: 0%
浏览 38

表单标签和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?

  • 写回答

1条回答 默认 最新

  • 乱世@小熊 2016-09-30 18:12
    关注

    This answer assumes jQuery use (which your question is not, kudos).

    One of the benefits of using the form tag is the serialization of the form. Allowing for a cleaner approach of passing form data to your processing page.

    It's also a bit cleaner (IMO) for form validation. Obviously there are many ways to validate form input but you can easily pass the form object and search for required elements having a valid value.

    Adapted from Ajax and Forms on Learn.jQuery.com.

    Although I would agree with celerno do what you need to do, but keep it at a minimum.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器