如何在来自 CoffeeScript、RoR 的 ajax 请求后检查我的服务器回滚事务
How to check if my server rollback transaction after ajax request from CoffeeScript, RoR
$.ajax
url: "/models"
type: "POST"
dataType: 'json'
data: {model: {name: "name", x: "x", y: "y"}}
有什么方法可以检查我的服务器是否接受了这个请求并保存了新元素而不再次发出服务器请求?
哦..我想通了
每次触发 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 中进行一些更改。
我想创建一些元素,所以 action "create" 看起来像这样:
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
$.ajax
url: "/models"
type: "POST"
dataType: 'json'
data: {model: {name: "name", x: "x", y: "y"}}
有什么方法可以检查我的服务器是否接受了这个请求并保存了新元素而不再次发出服务器请求?
哦..我想通了
每次触发 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 中进行一些更改。 我想创建一些元素,所以 action "create" 看起来像这样:
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