整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

HTML5基础学习 19-表单

TML5 Forms

HTML5 brings many features and improvements to web form creation. There are new attributes and input types that were introduced to help create better experiences for web users.

Form creation is done in HTML5 the same way as it was in HTML4:

HTML5为Web表单创建带来了许多功能和改进。 引入了新的属性和输入类型,以帮助为网络用户创造更好的体验。

HTML中的表单创建方式与HTML4中一样:

1 新属性 New Attributes

HTML5 has introduced a new attribute called placeholder. On <input> and <textarea> elements, this attribute provides a hint to the user of what information can be entered into the field.

HTML5引入了一个名为placeholder的新属性。 在<input>和<textarea>元素上,此属性向用户提供可以在该字段中输入哪些信息的提示。

The autofocus attribute makes the desired input focus when the form loads:

2 Forms with Required Fields

The "required" attribute is used to make the input elements required.

The form will not be submitted without filling in the required fields.

The autocomplete attribute specifies whether a form or input field should have autocomplete turned on or off.When autocomplete is on, the browser automatically complete values based on values that the user has entered before.

autocomplete属性指定表单或输入字段是否应该启用或禁用自动完成。

当自动填充开启时,浏览器会根据用户之前输入的值自动完成值。

HTML5添加了几种新的输入类型:- color- date- datetime- datetime-local- email- month- number- range- search- tel- time- url- weekNew input attributes in HTML5:- autofocus- form- formaction- formenctype- formmethod- formnovalidate- formtarget- height and width- list- min and max- multiple- pattern (regexp)- placeholder- required- step

3 搜索框 Creating a Search Box

Search Options

The <datalist> tag can be used to define a list of pre-defined options for the search field:

<datalist>标签可用于定义搜索字段的预定义选项列表:

<option> defines the options in a drop-down list for the user to select. The ID of the datalist element must match with the list attribute of the input box.

<option>在用户选择的下拉列表中定义选项。

datalist元素的ID必须与输入框的list属性相匹配。

Creating More Fields

Some other new input types include email, url, and tel:

These are especially useful when opening a page on a modern mobile device, which recognizes the input types and opens a corresponding keyboard matching the field's type:

当在现代移动设备上打开页面时,这些功能特别有用,它识别输入类型并打开与字段类型匹配的相应键盘:

These new types make it easier to structure and validate HTML forms.

这些新类型使得HTML表单更易于构造和验证。

文地址:https://www.cnblogs.com/zhanglei93/p/6273655.html

作者:best.lei

数据绑定和表单标签

  • 数据绑定

数据绑定是将用户输入绑定到领域模型的一种特性,在Spring MVC的controller和view数据传递中,基于HTTP请求的特性,所有HTTP请求参数的类型均为字符串,如果模型领域需要绑定的类型为double或int,则需要手动进行类型转换,而有了数据绑定后,就不需要手动将HTTP请求中的String类型转换为模型需要的类型了,数据绑定的另一个好处是,当输入验证失败时,会重新生成一个HTML表单,无需重新填写输入字段。

  • 表单标签库

表单标签库中包含了可以用在JSP页面中渲染HTML元素的标签。为了使用这些标签,必须在JSP页面开头处声明taglib指令。

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

表单标签库中有input、password、hidden、textarea、checkbox、checkboxes、radiobutton、radiobuttons、select、option、options、errors。表单标签有acceptCharset、commandName、cssClass、cssStyle、htmlEscape、modelAttribute等属性。

  1. input标签:input标签渲染<input type="text"/>元素,这个标签最重要的是path属性,该字段将输入绑定到form backing object的一个属性。如下所示,这个input标签被绑定到了user对象的userName属性上
<form:form modelAttribute="user" method="post" action="userSave">
 <fieldset>
 <p>
 <label for="name">用户名:</label>
 <form:input path="userName"/>
 </p>
 </fieldset>
</form:form>
  1. password标签:渲染<input type="password"/>元素,password标签与input标签相似,只不过它有一个showPassword属性。
  2. textare标签:渲染一个HTML的textarea元素。textarea基本上就是支持多行输入的input元素。
  3. checkbox标签:渲染<input type="checkbox"/>元素,同样是通过path属性实现数据绑定,同时checkboxes渲染多个checkbox元素。
  4. radiobutton标签渲染<input type="radio"/>元素,radiobuttons渲染多个radio元素。
  5. select标签:渲染一个HTML的select元素,被渲染元素的选项可能来自赋予其items属性的Collection、Map、Array,或者来自一个嵌套的option或options标签。
  • 数据绑定范例

如上分别介绍了数据绑定的定义和优势,以及一些表单标签,为了让大家能进一步了解上面的内容,范例中实现了用户类属性和JSP中表单的绑定,同时在JSP中分别展示了input、password、textarea、checkbox、select标签。

我们首先看一下User类,类中包含User的属性,以及对属性字段的get和set方法:

public class User {
 private String userName; //用户名
 private String password; //密码
 private Integer sex; //性别
 private boolean marriage; //是否结婚
 private ArrayList<String> hobby; //兴趣爱好
 private ArrayList<String> contacts;//人脉
 private String carrer; //职业
 private String houseRegister; //户籍
 private String remark; //个人描述
 public String getRemark() {
 return remark;
 }
 public void setRemark(String remark) {
 this.remark = remark;
 }
 public String getHouseRegister() {
 return houseRegister;
 }
 public void setHouseRegister(String houseRegister) {
 this.houseRegister = houseRegister;
 }
 public String getCarrer() {
 return carrer;
 }
 public void setCarrer(String carrer) {
 this.carrer = carrer;
 }
 public String getUserName() {
 return userName;
 }
 public void setUserName(String userName) {
 this.userName = userName;
 }
 public String getPassword() {
 return password;
 }
 public void setPassword(String password) {
 this.password = password;
 }
 public Integer getSex() {
 return sex;
 }
 public void setSex(Integer sex) {
 this.sex = sex;
 }
 public boolean isMarriage() {
 return marriage;
 }
 public void setMarriage(boolean marriage) {
 this.marriage = marriage;
 }
 public ArrayList<String> getHobby() {
 return hobby;
 }
 public void setHobby(ArrayList<String> hobby) {
 this.hobby = hobby;
 }
 public ArrayList<String> getContacts() {
 return contacts;
 }
 public void setContacts(ArrayList<String> contacts) {
 this.contacts = contacts;
 }
}

我们的Controller类中定义映射请求的方法,其中包括处理userInput请求的inputUser方法,以及userSave请求的addUser方法,其中在addUser方法中用到了重定向。其中通过@Autowired注释在ProductController对象中主动注入UserService对象,实现对user对象的保存和查询等操作;通过model的addAttribute方法将User类对象、HashMap类型的hobbys对象、String[]类型的carrers对象传递给View(JSP),代码如下:

同时,为了避免中文乱码的问题,需要在web.xml文件中增加编码过滤器,同时JSP页面编码设置为UTF-8,form表单的提交方式必须为post,我们先看web.xml文件的配置信息:

UserAddJSP文件格式如下,其中将Map类型的hobbys绑定到了checkboxes上,将String[]类型的carrer绑定到了select上,实现了通过option标签对select添加选项,同时method方法需指定为post来避免中文乱码的问题。

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Add a User</title>
</head>
<body>
<div id="global">
<form:form modelAttribute="user" method="post" action="userSave">
 <fieldset>
 <legend>Add a User</legend>
 <p>
 <label>用户名:</label>
 <form:input path="userName"/>
 </p>
 <p>
 <label>密码:</label>
 <form:password path="password"/>
 </p>
 <p>
 <label>婚姻:</label>
 <form:checkbox path="marriage" value="已婚"/>
 </p>
 <p>
 <label>爱好:</label>
 <form:checkboxes items="${hobbys}" path="hobby"/>
 </p>
 <p>
 <label>人脉:</label>
 <form:checkbox path="contacts" value="张三"/>张三
 <form:checkbox path="contacts" value="李四"/>李四
 <form:checkbox path="contacts" value="王五"/>王五
 <form:checkbox path="contacts" value="赵六"/>赵六
 </p>
 <p>
 <label>职业:</label>
 <form:select path="carrer"> 
 <option/>请选择职业
 <form:options items="${carrers }"/>
 </form:select>
 </p>
 <p>
 <label>户籍:</label>
 <form:select path="houseRegister">
 <option>请选择户籍</option>
 <option value="1">北京</option>
 <option value="2">上海</option>
 <option value="3">广州</option>
 <option value="4">深圳</option>
 <option value="5">其它</option>
 </form:select>
 </p>
 <p>
 <label>个人描述:</label>
 <form:textarea path="remark" rows="5"/>
 </p>
 <p id="buttons">
 <input id="reset" type="reset">
 <input id="submit" type="submit" value="Add User">
 </p>
 </fieldset>
</form:form>
</div>
</body>
</html>

UserList.JSP文件实现对保存的user信息的遍历展示。

因为该工程是在上一篇工程中增加的,因此其他的配置文件与上一篇工程中相同,这里不再做过多的赘述,希望读者见谅。

运行该程序在浏览器中输入http://localhost:8081/SpringMVC/userInput可以看到左图,填写表单完成,点击Add User按钮,即可看到右图的输出信息,不知道读者是否发现输出信息中存在问题,兴趣爱好为[1],户籍也为1,输出的为表单中选择的索引位置,还有好像保单中忘了指定User的性别了,导致输入性别列为空。这些问题是由于本文的疏忽造成的,有兴趣的读者可以对这篇博客做更加完善的改正,谢谢阅读!

天内容好长,翻译起来有点累。

Preparations

With the basics of HTTP out of the way, let's get acquainted with the tools we'll use in this book to demonstrate how HTTP works. This section goes through a few tools you'll need to follow along. Note that you only need one of the tools listed. It is important to note that you will be able to follow this book regardless of what tool you use, so pick one that you're comfortable with and get started!

翻译:

准备工作,我们先学习下工具来演练 HTTP怎么工作的。本章节介绍下一些工具,可以选择一个你觉得比较合适的来上手。

HTTP GUI Tools

We'll make heavy use of Graphical HTTP tools throughout this book. There are lots of options available in this category of HTTP tools, and we'll be using Paw 3. Although it's a paid App in the Mac App Store, there is a limited Trial version as well which can get you through the book.

That said, there are many other alternatives out there. Some other capable options are Insomnia and Postman; they're both free and they work on OS X, Windows, and Ubuntu.

HTTP 的 图形用户界面工具

我们这里用的是Paw3, 虽然他需要在苹果商店买,但是也有短时间免费版本。

你也可以选择 Insomnia 和 Postman (译者之前装过postman,这里就用Postman了)

HTTP Command line Tools

curl is a free command line tool that is used to issue HTTP requests.

Mac OS X/Linux :

It is shipped with OS X and most GNU/Linux distributions, and you can simply invoke it on the command line by issuing the command below.

$ curl www.google.com

If you have version 1803 or later of Windows 10, cURL should be installed by default. If you have an earlier version of windows or cannot find cURL on your version, we recommend installing a GUI version of cURL. You won't be able to execute the command line commands, but you should still be able to perform the appropriate actions in the GUI.

curl 是一个免费的工具,用来发送HTTP 请求,和MAC 及绝大多数 Linux 系统原生绑定。

你可以很简单的启动curl ,用下面命令行:

$ curl www.google.com

如果你有windows10的 1803 及以后版本,curl 也是默认安装好了,如果你有更早的版本,你可以考虑安装一个,图形界面的curl. 你虽然没法执行命令,但是可以在GUI 中执行相关操作。

Making HTTP Requests

HTTP Request with a Browser

Making an HTTP request is easy. Say you want to visit Reddit in your browser. All you need to do is launch your browser and enter the address https://www.reddit.com and

this is a snapshot of what you might see:

翻译:

做HTTP的申请

通过一个浏览器做HTTP请求,做HTTP请求很容易,你可以在浏览器中访问reddit ,直接键入地址https://www.reddit.com, 然后看到快照。



The server that hosts the main Reddit website handles your request and issues a response back to your browser. Your browser is smart enough to process the response that is sent back and display the site you see in the screenshot, with all its colors, images, text and presentation.

翻译:

承载着Reddit web主站的服务器负责处理请求,并返回一个response 到浏览器,浏览器足够“聪明”可以处理返回的响应文件,在屏幕上把文件展示出来,包含的是颜色、图片、文字和展示。

HTTP Request with an HTTP Tool

Because browsers show us the processed version of the response, we don't get to see the raw response the server sent back. How do we see the raw HTTP response data?

For that, we can use an HTTP tool and just like the browser did when we entered a URL in the address bar, we can have our HTTP tool issue a request to https://www.reddit.com.

Our HTTP tool, Paw, doesn't process the response and lets us see the raw response data, which looks something like this:

通过工具来做HTTP请求

因为浏览器显示的是服务端回复(response)被 处理后的版本,我们没拿到服务器发回来原始的回复,我们怎么查看 服务器返回的HTTP 裸回复呢?

我们可以用HTTP工具 来实现,我们在地址栏输入URL, 我们的HTTP工具会发送一个请求到 https://www.reddit.com.我们的HTTP 工具,Paw,不会处理服务端的回复(response),那原始回复的response 是什么样呢?如下图



What a huge difference this raw response is from the display in your browser! If you've never seen raw HTTP response data before, this may be quite shocking. What you see here is, in fact, what your browser also receives, except it parses and processes that huge blob of data into a user-friendly format.

If you're learning about HTTP in order to become a web developer, you'll need to learn to read and process raw HTTP response data just by scanning it. Of course, you won't be able to convert it into a high-resolution picture in your head, but you should have a general idea of what the response is about. With enough experience, you can dig into the raw data and do some debugging and see exactly what's in the response.

这个和在浏览器上显示的有很大的区别! 你的浏览器也会受到一样的裸回复(response)数据,浏览器可以对回复数据进行解析,并以一个友好的方式向用户呈现出来。

如果你在学习HTTP ,目的是做一个web 开发者,你需要学习和读懂如何处理这些裸数据(response).当然,你无法把response转换为头脑中一个高精度的照片,但是你应该大概了解这个回复是什么含义。只要有足够的经验,你就可以阅读这些裸数据,并做一些调试工作,看看回复(response)是什么。

我在Postman 里面输入地址后,打开console,也可以看到下面返回的裸回复。



Using the Inspector

Every modern browser has a way to view HTTP requests and responses, and it's usually called the inspector. We're going to use the Chrome Inspector to demonstrate how to analyze your browser's HTTP communication.

Launch Chrome browser and open the Inspector by navigating to the Chrome Menu on the top right-hand corner of your browser. Select Tools > More Tools > Developer Tools. There are other ways of accessing the inspector, such as right-clicking and selecting the 'Inspector' option, or using a keyboard shortcut Ctrl+Shift+I (or Option+Command+I on a Mac).

Send a new request to Reddit by entering the address https://www.reddit.com into your browser.

With the inspector still open click on the Network tab:

翻译:

使用检查员(inspector)

每一个现代的浏览器都有办法可以读HTTP 请求和回复请求,这个方式就是检查员。我们将使用google 浏览器Chrome 的检查员(inspector)来分析浏览器的HTTP通信。

  1. 启动google 浏览器,打开inspector, 通过 select tools->More Tools>developer tools
  2. 发送一个请求到reddit, 在浏览器中键入地址 https://www.reddit.com
  3. 在inspector 中打开network 表。

国内访问,果然时间要长很多。

4. The first thing you should notice is that there are a lot of entries there. Each entry is a separate request, which means just by visiting the URL,

your browser is making multiple requests, one for every resource (image, file, etc.). Click on the first request for the main page, www.reddit.com entry:

翻译:

首先需要知道的是,这里很多的条目,每个条目是一个单独的请求。这意味着(敲黑板),即使只是访问url,你的浏览器已经做了多个request,针对每个资源会申请一次(资源包括图片、文件等等)。鼠标点击主页条目看一下,www.reddit.com 条目:



From here, you'll be able to see the specific request headers, cookies as well as the raw response data:



翻译:

这里可以看到针对这个主页的请求,cookie 以及裸回复(response)。

The response data should look similar to what we saw earlier using our HTTP tool, except Chrome displays the data in a single line.

Another thing to note when using the inspector's Network tab is, other than the first request, there are a ton of other requests returned:

翻译:

回复的数据应该和之前我们用HTTP 工具 看到的内容是相似的,区别是google 浏览器在单行中显示数据。(这里在新版本google 浏览器已经改过来了)

另外一个需要关注的是,使用inspector network 这个表,除了看到第一个请求,还有非常多的其它请求返回。(如下图)



Why are these additional responses sent back, who initiated the requests? What's happening is that the resource we requested, the initial www.reddit.com entry, returned some HTML. And in that HTML body are references to other resources like images, css stylesheets, javascript files and more. Your browser, being smart and helpful, understands that in order to produce a visually appealing presentation, it has to go and grab all these referenced resources. Hence, the browser will make separate requests for each resource referenced in the initial response. When you scroll down the Network tab, you'll be able to see all the referenced resources. These other requests are to make sure the page displays properly on your screen, among other things. Overall, you see that the browser's inspector gives you a good feel for these referenced resources. A pure HTTP tool, on the other hand, returns one huge response chunk without any concern for automatically pulling in referenced resources. A curl request will demonstrate this:

翻译:

为什么会有额外的回复被发回来? 第一个请求条目,www.reddit.com 返回来一些HTML 的文件。这个文件指向了其它的资源,比如图片、CSS、JS 文件。而你的浏览器足够聪明和帮助,理解了这个HTML,并去抓去了所有相关的资源。

这样,在最开始的回复后,浏览器会针对每个资源做单独的申请。当你在network 表往下查看所有的表,你能够看到所有被引用的资源。这些其它的请求可以帮助你把页面在你的屏幕显示的更加清晰,总的来看,浏览器inspector 给你一个好的感觉,针对所有的资源。

一个纯HTTP 工具,只会返回一个巨大的response 片段,不会考虑自动的去把关联到的资源拉群进来。一个curl 工具一般显示的内容如下:

Reddit now requires that we add in a User-Agent to our HTTP requests. Otherwise, it will deny our request, assuming that the request originates from a bot.

Make sure to append the following to any curl commands where reddit is the site you wish to send a request to.

-A 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36'

The -A option is used to specify a User-Agent for an HTTP request when using curl. Since this is another option for our command,

don't forget to add in a space between -v and -A.

For the sake of simplicity, we specify the User-Agent that is listed at the end of this page. You may use your own User-Agent as well.

$ curl -X GET "https://www.reddit.com/" -m 30 -v

What you should see is just one request and the response containing the HTML, but no additional requests being automatically issued, like you see in a browser.

翻译:

下图,curl 百度的效果图:



Request Methods

Let's revisit the diagram from Step 3 above, when we looked at the responses in the Network tab. You might have noticed two columns named Method and Status.

If you don't see the Methodcolumn, it may be hidden by default. To display the Method column, right click on Status and select Method.

The Method column should now be visible next to the Status column.

翻译:

请求方法

让我们重新调到第三步(在google浏览器inspector那一步),我们在network 里面查看responses的时候,你可以看到两列:method 和 status.在status 状态上右键,选择展示method,如下图。



We'll spend this section looking at what the information shown in these columns mean.

Information displayed in the Method column is known as the HTTP Request Method. You can think of this as the verb that tells the server what action to perform on a resource. The two most common HTTP request methods you'll see are GET and POST. When you think about retrieving information, think GET, which is the most used HTTP request method. In the above diagram, you'll notice almost all of the requests use GET to retrieve the resources needed to display the web page.

The Status column shows the response status for each request. We'll talk about responses in detail later in the book. The important thing to understand is that every request gets a response, even if the response is an error -- that's still a response. (That's not 100% technically true as some requests can time out, but we'll set those rare cases aside for now.)

我们将花一点时间介绍下这些列里包含信息的含义。

  • 1. 在method列里显示的是HTTP Get method, 你可以理解为 告诉服务器来针对一个资源能做一个操作。
  • 2. 见的最多的request 方法是GET 和POST.

当你想获取信息,用GET 方法,这是最常用的HTTP 请求方法,在上面的请求中,你可以看到几乎所有的请求都是GET .状态列显示 每个请求的返回状态,我们在本书稍后会介绍状态的含义。需要了解的是,每一个请求都会有一个回复(response),即使回复还是错误的,这仍然是一个回复。(当然有些超时的除外)

GET Requests

GET requests are initiated by clicking a link or via the address bar of a browser. When you type an address like https://www.reddit.com into the address bar of your browser, you're making a GETrequest. You're asking the web browser to go retrieve the resource at that address, which means we've been making GET requests throughout this book. The same goes for interacting with links on web applications. The default behavior of a link is to issue a GET request to a URL. Let's make a simple GET request to https://www.reddit.com with an HTTP tool. Make sure to select GET and enter the address:



You can view the raw HTTP response and other information sent back from the web server on the right panel.curl users can enter the following command on their terminal:

$ curl -X GET "https://www.reddit.com/" -m 30 -v

We can also send query strings using an HTTP tool. Let's look at another quick example by sending a request to search for all things Michael Jackson at https://itunes.apple.com/ with query strings. The final URL will look like this:

https://itunes.apple.com/search?term=Michael%20Jackson

before submitting a request, make sure to select GET.



Here we are simply sending an HTTP GET request to the server at https://itunes.apple.com/ with parameter term=Michael%20Jackson where %20 is a URL-encoded character for SPACE.

The curl command for this example is:

$ curl -X GET "https://itunes.apple.com/search?term=Michael%20Jackson" -m 30 -v

That's all you need to know about issuing HTTP GET requests for now. The primary concepts are:

  • GET requests are used to retrieve a resource, and most links are GETs.
  • The response from a GET request can be anything, but if it's HTML and that HTML references other resources, your browser will automatically request those referenced resources.
  • A pure HTTP tool will not.

翻译

你需要了解的是:

  • Get 请求主要目的是获取资源的,绝大多数链接就是GET
  • 从GET 请求里面拿到的反馈可以是任何东西,如果是HTML,而且HTML 包含了其它资源,浏览器会自动的请求这些被引用的资源。
  • 而一个纯的HTTP 工具不会这样做(自动抓取html 中的引用resource)

POST Requests

We've seen how to retrieve or ask for information from a server with GET, but what if you need to send or submit data to the server? That's where another essential HTTP request method comes in: POST. POST is used when you want to initiate some action on the server, or send data to a server. Let's see an example with our HTTP tool:

翻译:

如果需要提交信息到服务器,这个时候需要使用HTTP 请求的另外一个方法,POST。 当你需要对服务器发起某些操作,或者发送数据到服务器,需要POST。



Here is the curl command:

$ curl -X POST "https://echo.epa.gov" -m 30 -v

The above screenshot shows a POST request to https://echo.epa.gov and the response from the server. Typically from within a browser, you use POST when submitting a form. POST requests allow us to send much larger and sensitive data to the server, such as images or videos. For example, say we need to send our username and password to the server for authentication. We could use a GET request and send it through query strings. The flaw with this approach is obvious: our credentials become exposed instantly in the URL; that isn't what we want. Using a POST request in a form fixes this problem. POST requests also help sidestep the query string size limitation that you have with GET requests. With POST requests, we can send significantly larger forms of information to the server.

Let's see another example of making a POST request by filling out a web form. Our sample form looks like this in the browser:

翻译:

curl 命令行如下:

$ curl -X POST "https://echo.epa.gov" -m 30 -v

  • Post 请求允许我们发送更大的、更敏感的信息给服务器,比如照片 或者视频。
  • 如果发送用户名和密码到服务器,使用GET 方法,这个时候我们的信息会被暴露,这不是我们希望做的。
  • 使用POST 方法,也不会在收到get 请求的大小限制,你可以发送大的多的信息给服务器。



After filling out the form, you'll be redirected to a page that looks like this:

Now let's switch over to our HTTP tool and simulate what we just did in the browser. Instead of filling out a form in the browser, we will send a POST request to http://al-blackjack.herokuapp.com/new_player. This is the URL that the first form (the one where we input a name) submits to:

翻译:

我们换到HTTP 工具上来模拟我们在浏览器上的操作,代替我们在浏览器上填入信息,我们会发送Post 请求到 http://al-blackjack.herokuapp.com/new_player

我们第一个表格(我们输入名字的)提交到这个url:



Note: You'll want to ensure that your Content-Type header is set to application/x-www-form-urlencoded. If it isn't, then your POST request won't be interpreted by the application correctly.

If you're using Paw 3, select the Form URL-Encoded tab instead of the Text tab.

If you're using Insomnia, make sure you click "Form URL Encoded" in the Body dropdown menu. And if you're using Postman, make sure the radio button for x-www-form-urlencodedis selected under the Body tab.

翻译:

你会希望保证你的 content-type header 为 application/x-www-form-urlencoded.如果不这样设置,服务器将无法识别请求。

如果选择postman,记得选择了 x-www-form-urlencode 按钮,在body表中。



译者在postman中的操作截图:



303 see other的含义:(from 译者)



Or you can use curl:

$ curl -X POST "http://al-blackjack.herokuapp.com/new_player" -d "player_name=Albert" -m 30 -v

Notice that in the screenshot and curl command we're supplying the additional parameter of player_name=albert. It has the same effect as inputting the name into the first "What's your name?" form and submitting it.

We can verify the contents using the inspector (right click and select Inspect). You'll see that the player_name parameter we're sending as part of the POST request is embedded in the form via the nameattribute of the input element:

翻译:

或者你可以用curl 命令实现 :

$ curl -X POST "http://al-blackjack.herokuapp.com/new_player" -d "player_name=Albert" -m 30 -v

这里 -d "player_name=Albert" 和在浏览器里面填入 “what's your name?”表格效果是一样的,可以在浏览器里面看到, player_name 参数是保存在表格里的。




But the mystery is, how is the data we're sending being submitted to the server since it's no

t being sent through the URL? The answer to that is the HTTP body.

The body contains the data that is being transmitted in an HTTP message and is optional. In other words, an HTTP message can be sent with an empty body.

When used, the body can contain HTML, images, audio and so on. You can think of the body as the letter enclosed in an envelope, to be posted.

The POST request generated by the HTTP tool or curl is the same as you filling out the form in the browser, submitting that form, and then being redirected to the next page.

Look carefully at the raw response in the HTTP tool screenshot. The key piece of information that redirects us to the next page is specified in the field Location:

http://al-blackjack.herokuapp.com/bet. Location and its associated data is part of what is known as an HTTP response header (yes, requests have headers too, but in this case,

it's a response header). Don't worry too much about this yet as we'll discuss headers in a later section. Your browser sees the response header and automatically issues a brand

new request to the URL specified in the Location header, thereby initiating a new, unrelated request. The "Make a bet" form you see is the response from that second request.

翻译:

不过疑问就在,这个数据是怎么提交到服务器上的,因为他没有通过URL 提交。

答案是:HTTP body (HTTP 身体)(敲黑板),HTTP body包含了传递给HTTP的数据,这个是可选的。

  • 另一句话说,HTTP 消息可以通过空body来传送。当使用HTTP body 传递,body里面可以包含HTML , 图片,声音 还有其它。
  • 你可以把body 理解为保存在信封里面的信,随时可以邮寄。
  • HTTP 工具发出的请求 或者 curl 发出的请求,和你在浏览器中填入表格是一样的,提交那个表格,然后被重定向到另外一个页面。
  • 可以 仔细的查看下HTTP 工具返回的原始response数据,关键信息让用户重定向到下一页是在 Location 这里定义:

http://al-blackjack.herokuapp.com/bet. ( request 请求有Header ,这里是response 的header信息)你的浏览器看到了response header, 自动发起了一个新的请求到url (location 字段里指定的),这样就看到了第二个response 表格。



Note: If you're using some other HTTP tool, like Insomnia or Postman, you may have to uncheck "automatically follow redirects" in order to see the Location response header.



If you're fuzzy on the previous paragraph, read it again. It's critical to understand that when using a browser, the browser hides a lot of the underlying HTTP request/response cycle from you. Your browser issued the initial POST request, got a response with a Location header, then issued another request without any action from you, then displayed the response from that second request. Once again, if you were using a pure HTTP tool, you'd see the Location response header from the first POST request, but the tool would not automatically issue a second request for you. (Some HTTP tools have this ability, if you check the "automatically follow redirects" option.)

翻译:

这里就是对上文的重复解释,不复述了。

HTTP Headers

HTTP headers allow the client and the server to send additional information during the request/response HTTP cycle. Headers are colon-separated name-value pairs that are sent in plain text. By using the Inspector, we can see these Headers. Below, you can see both the request as well as the response headers:

The above shows the various headers being transmitted during a request/response cycle. Further, we can see that the request and response contain a different set of headers under Request Headers:

The above shows the various headers being transmitted during a request/response cycle.

Further, we can see that the request and response contain a different set of headers under Request Headers:



Request Headers

Request headers give more information about the client and the resource to be fetched. Some useful request headers are:



Don't bother memorizing any of the request headers, but just know that it's part of the request being sent to the server. We'll talk about response headers in the next chapter.

翻译:

这里讲了request header 的一些信息,request header 和 response header 信息是不一样的。

上图里request header 里面包含有:主机名、接受的语言、用户端agent 信息、连接信息。

Summary

This was a brief introduction on making HTTP requests. After going through this section, you should be comfortable with:

  • using the inspector to view HTTP requests
  • making GET/POST requests with an HTTP tool
  • The most important components to understand about an HTTP request are:
  • HTTP method
  • path
  • headers
  • message body (for POST requests)

In the next chapter, we'll continue learning about HTTP by looking at HTTP responses.

翻译:

本章节介绍了下HTTP requests 信息,

经过本章节,你可以:

使用inspector 来 查看HTTP requests 请求

使用HTTP 工具来发起GET /POST 请求

最需要了解的组件包括:

HTTP 方法

路径

headers 头部

消息体(针对post 请求)