当前位置:  首页>> 技术小册>> 编程入门课:HTML(5)从入门到实战

表单数据的提交是指将用户填写的表单数据传递到后台服务器进行处理。在HTML中,表单数据的提交方式主要有两种:GET和POST。

一、GET方式提交表单数据

使用GET方式提交表单数据时,表单数据将会以查询字符串的形式附加在URL后面,例如:

  1. <form action="http://example.com/search" method="get">
  2. <input type="text" name="q">
  3. <button type="submit">搜索</button>
  4. </form>

在用户点击提交按钮时,表单数据将会以如下形式提交到后台服务器:

  1. http://example.com/search?q=xxx

其中,action属性指定表单数据提交的URL,method属性指定提交方式为GET。

二、POST方式提交表单数据

使用POST方式提交表单数据时,表单数据将会被包含在HTTP请求体中,例如:

  1. <form action="http://example.com/login" method="post">
  2. <input type="text" name="username">
  3. <input type="password" name="password">
  4. <button type="submit">登录</button>
  5. </form>

在用户点击提交按钮时,表单数据将会以HTTP请求体的形式提交到后台服务器。

  1. POST /login HTTP/1.1
  2. Content-Type: application/x-www-form-urlencoded
  3. username=xxx&password=xxx

其中,action属性指定表单数据提交的URL,method属性指定提交方式为POST。需要注意的是,POST方式提交表单数据需要设置Content-Type为application/x-www-form-urlencoded,同时表单数据需要以key-value形式编码,例如key1=value1&key2=value2。

三、AJAX方式提交表单数据

除了以上两种常规的表单数据提交方式,还可以使用AJAX方式提交表单数据。使用AJAX方式提交表单数据可以在不刷新页面的情况下进行数据提交和处理,提升用户体验。下面是一个使用jQuery实现的AJAX方式提交表单数据的示例:

  1. <form id="myForm">
  2. <input type="text" name="username">
  3. <input type="password" name="password">
  4. <button type="submit">登录</button>
  5. </form>
  1. $(document).ready(function() {
  2. $("#myForm").submit(function(event) {
  3. event.preventDefault(); // 阻止表单默认提交行为
  4. var formData = $(this).serialize(); // 将表单数据序列化
  5. $.ajax({
  6. url: "http://example.com/login",
  7. type: "POST",
  8. data: formData,
  9. success: function(result) {
  10. // 处理返回结果
  11. },
  12. error: function() {
  13. // 处理异常情况
  14. }
  15. });
  16. });
  17. });

在以上代码中,preventDefault()方法用于阻止表单的默认提交行为,serialize()方法用于将表单数据序列化为字符串,$.ajax()方法用于发起AJAX请求。在success回调函数中可以处理返回结果,在error回调函数中可以处理异常情况。


该分类下的相关小册推荐: