【问题标题】:How to check if my server rollback transaction after ajax request from CoffeeScript, RoR如何在来自 CoffeeScript、RoR 的 ajax 请求后检查我的服务器是否回滚事务
【发布时间】:2015-08-12 09:12:48
【问题描述】:
$.ajax
url: "/models"
type: "POST"
dataType: 'json'
data: {model: {name: "name", x: "x", y: "y"}}
有什么方法可以检查我的服务器是否接受了这个请求并保存了新元素而不再次发出服务器请求?
【问题讨论】:
标签:
ruby-on-rails
ajax
coffeescript
rollback
【解决方案1】:
哦..我想通了。
每次触发 ajax 请求时,它都会等待服务器响应一些数据。 (在我的例子中是 json 格式的数据)
我在 coffescript 中的 ajax 请求现在看起来像这样:
$.ajax
url: "/models"
type: "POST"
dataType: 'json'
data: {model: {name: "name", x: "x", y: "y"}}
success: (data) ->
alert "Request was send to the server and server axcepted what I wanted to say … but I don't know if he do what I've told to him"
error: (data) ->
alert "The server says that he couldn't do what I've told him becouse of error number: #{JSON.stringify(data['status'])}"
在这种情况下,最重要的是让服务器实际响应一些预期错误的值。
所以……需要在 Controller 中进行一些更改。
我想创建一些元素,所以“创建”动作看起来像这样:
def create
@model = Model.new(model_params)
respond_to do |format|
if @model.save
format.html { render :nothing => true }
format.json { render :json => @model, :status => :ok}
else
format.html { ender :nothing => true }
format.json { render json: @model.errors, status: :unprocessable_entity }
end
end
end
:unprocessable_entity 发送错误 #422