chatroom.coffee中的js代码:
document.addEventListener 'turbolinks:load', ->
document.getElementById("new_message").addEventListener "keypress", (e) ->
if e && e.keyCode == 13
e.preventDefault();
this.submit();
return
return
MessagesController的action方法
def create
message = @chatroom.messages.new(message_params)
message.user_id = current_user.id
message.save
end
在/chatroom/1中的输入框回车后,jS代码请求是成功的,但是是302。同时跳到了问题界面:
MessagesController#create is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: []
log:
Started POST "/chatrooms/1/messages" for 127.0.0.1 at 2018-07-17 17:45:15 +0800
Processing by MessagesController#create as HTML
...在message 已经commit后,提示:
Completed 406 Not Acceptable in 38ms (ActiveRecord: 1.7ms)
请求实际已经处理,但提示406表示请求的资源的内容特性无法满足请求头中的条件,因而无法生成响应实体,该请求不可接受。
因为create方法并没有给一个response的返回方法redirect_to.
另外请求不是一个Javascript 请求。也奇怪,应该是js请求才对。
没有有效请求。submit()有bug。
使用Rails.ajas自定义请求:
url = this.action
# Rails.serializeElement()是一个UJS脚本方法。或者使用传统的FormData(this)
data = new FormData(this)
# data = Rails.serializeElement(this)
Rails.ajax({
type: "POST"
url: url
data: data
dataType: "json"
})