Javascript 使用'格式;远程:true';即使使用重定向也返回200响应
我有一个带有Javascript 使用'格式;远程:true';即使使用重定向也返回200响应,javascript,ruby-on-rails,Javascript,Ruby On Rails,我有一个带有remote:true的表单,如下所示: Started POST "/transfers" for ::1 at 2019-06-04 08:32:22 -0700 Processing by TransfersController#create as JS ... Redirected to http://localhost:3000/transfers Completed 200 OK in 1476ms (ActiveRecord: 81.2ms) Started GET
remote:true
的表单,如下所示:
Started POST "/transfers" for ::1 at 2019-06-04 08:32:22 -0700
Processing by TransfersController#create as JS
...
Redirected to http://localhost:3000/transfers
Completed 200 OK in 1476ms (ActiveRecord: 81.2ms)
Started GET "/transfers" for ::1 at 2019-06-04 08:32:23 -0700
Processing by TransfersController#index as HTML
我的控制器create
操作如下所示:
Started POST "/transfers" for ::1 at 2019-06-04 08:32:22 -0700
Processing by TransfersController#create as JS
...
Redirected to http://localhost:3000/transfers
Completed 200 OK in 1476ms (ActiveRecord: 81.2ms)
Started GET "/transfers" for ::1 at 2019-06-04 08:32:23 -0700
Processing by TransfersController#index as HTML
def创建
@转账=@account.transfers.build(转账参数)
回应待办事项|格式|
如果@transfer.save
format.html{重定向到传输路径}
其他的
format.js
结束
结束
结束
如果我提交了一个没有错误的表单,页面就会像预期的那样重定向。但是,我注意到服务器的响应状态代码是200,而不是302。我的服务器日志如下所示:
Started POST "/transfers" for ::1 at 2019-06-04 08:32:22 -0700
Processing by TransfersController#create as JS
...
Redirected to http://localhost:3000/transfers
Completed 200 OK in 1476ms (ActiveRecord: 81.2ms)
Started GET "/transfers" for ::1 at 2019-06-04 08:32:23 -0700
Processing by TransfersController#index as HTML
只是想知道为什么是200而不是302?我还意识到这根本不应该起作用,因为我不应该用AJAX请求重定向(remote:true
发送AJAX请求,如果我理解正确的话)
关于SO上其他问题的答案似乎表明,redirect\u to
不起作用,我必须使用JS设置重定向的窗口位置。一些示例回答:
我不明白为什么我的代码能工作。有人能解释一下吗?我怀疑他在幕后施了魔法,但我不确定。具体地说,我怀疑,但我不太擅长JS,我不能解析很多。我也在运行Rails 5.2.1 首先,
form\u with
不使用remote
,它使用local
,默认设置为false
,也就是说,与form\u for
withremote:true
类似
其次,respond\u to
并不像您认为的那样有效。您不选择响应格式,客户机选择
如果客户端发送一个常规HTTP请求(remote:false
),则您的create
会在format.html
之后用块响应。如果客户端发送一个AJAX请求(remote:true
),那么create
将使用format.js
部分进行响应
没有重定向,因为自从发出AJAX请求以来,format.html{redirect\u to transfers\u path}
从未运行过
在浏览器的devel工具的“网络”选项卡中检查响应,以了解实际情况
另外,重构您的方法:
def创建
@转账=@account.transfers.build(转账参数)
saved=@transfer.save
回应待办事项|格式|
format.html做什么
如果保存
重定向到传输路径
其他的
flash.now[:注意]=“错误”
渲染:新
结束
结束
format.js#创建应用程序/视图//Create.js.erb和
#更新页面那里
结束
结束
正在进行重定向。在我成功发布转账后,我的页面确实会转到/transfers
。这是我最困惑的部分。我也有一个create.js.erb
,但严格来说,它是用来处理错误的,我发现即使我删除了该文件,在我发布传输后,页面仍然重定向,并且仍然用200代码响应。你检查过devel工具的“网络”选项卡吗?反应如何?它的类型是什么?是的,我检查了网络选项卡,响应的类型是xhr
,状态是200
。这个重定向怎么样:重定向到http://localhost:3000/transactions/pending
?操作是否挂起
发出获取索引
?啊,很抱歉,我意识到我复制了错误的路径。我已经编辑了我的问题,但是http://localhost:3000/transactions/pending
应该是http://localhost:3000/transfers
。我的Transfer#create
正在重定向到Transfer#index
。