Skip to Content
Node与Express开发(第2版)
book

Node与Express开发(第2版)

by Ethan Brown
June 2021
Intermediate to advanced
290 pages
9h 21m
Chinese
Posts & Telecom Press
Content preview from Node与Express开发(第2版)
80
|
第
8
章
8.4
 处理表单的不同做法
如果不使用
Ajax
,就只能通过浏览器提交表单了,这样做的结果是会刷新页面。不过,页
面要
怎样
刷新由你决定。当处理表单时,有两件事情需要考虑:由哪个路径处理这个表单
(表单中的
action
)以及给浏览器返回什么样的响应。
如果使用
method="POST"
(这是推荐做法),那么显示表单和处理表单都使用同一个路径也
是相当常见的。不过,它们是可以区分的,因为显示表单是一个
GET
请求,而处理表单是
一个
POST
请求。如果采取这种做法,就可以忽略表单的
action
属性。
另一个选择是使用另外的路径来处理表单。例如,如果联系信息页使用了路径
/contact
,可
以使用路径
/process-contact
来处理表单
(通过指定
action="/process-contact"
)。如果采
取这种做法,就可以选择使用
GET
来提交表单(我不推荐这样做,因为在
URL
上暴露表
单的字段毫无必要)。如果有多个
URL
是同样的提交途径
(例如,网站的多个页面都有使
用邮箱地址的注册框),那么为表单提交提供单独的端点或许会更好。
不管用什么路径来处理表单,都需要决定给浏览器返回什么样的响应。你有以下几种选择。
直接 HTML 响应
处理完表单之后,可以直接把
HTML
发回浏览器
(比如说一个视图)。如果试图刷新页
面,浏览器就会给出一条警告信息。而且这样做还会影响到浏览器的书签和返回按钮。
所以,不推荐这种做法。
302 重定向
尽管这是常见的做法,但它是对
302
(已找到)状态码最初含义的误用。
HTTP
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
精通模块化JavaScript

精通模块化JavaScript

Nicolás Bevacqua
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787115565099