gpt4 book ai didi

javascript - Ruby on Rails - 更新 ajax 的 PUT 方法

转载 作者:可可西里 更新时间:2023-11-01 02:30:31 25 4
gpt4 key购买 nike

谁能告诉我为什么这个 PUT 方法不起作用。

$.ajax({
type: "PUT",
dataType: "script",
url: '/resources/35',
data:
{
resource : { pos_y: 45, pos_x: 50 }
}
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});

服务器说我使用了GET 方法 但在我的ajax 请求中我有type: "PUT"

Started GET "/resources/35?resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&_=1344001820350" for 192.168.1.89 at 2012-08-03 15:50:20 +0200
Processing by ResourcesController#show as */*
Parameters: {"resource"=>{"pos_y"=>"45", "pos_x"=>"50"}, "_"=>"1344001820350", "id"=>"35"}
User Load (0.3ms) SELECT "users".* FROM "users"
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "35"]]
Rendered resources/show.html.erb within layouts/login (2.3ms)
Completed 200 OK in 238ms (Views: 235.9ms | ActiveRecord: 0.4ms)

资源 Controller .rb

 # PUT /resources/1                                                                                                                                                             
# PUT /resources/1.json
def update
@resource = Resource.find(params[:id])

respond_to do |format|
if @resource.update_attributes(params[:resource])
format.html { redirect_to @resource, notice: 'successfully updated.' }
format.js
else
format.html { render action: "edit" }
format.js
end
end
end

我试过添加_method: 'put' 但还是一样

$.ajax({
type: "PUT",
dataType: "script",
url: '/resources/35',
data:
{
resource : { pos_y: 45, pos_x: 50 },
_method: 'put'
}
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});

服务器:

"resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&method=put&=1344004390840"

Started GET "/resources/35?resource%5Bpos_y%5D=45&resource%5Bpos_x%5D=50&_method=put&_=1344004390840" for 192.168.1.89 at 2012-08-03 16:33:10 +0200
Processing by ResourcesController#show as */*
Parameters: {"resource"=>{"pos_y"=>"45", "pos_x"=>"50"}, "_"=>"1344004390840", "id"=>"35"}
User Load (0.3ms) SELECT "users".* FROM "users"
Resource Load (0.1ms) SELECT "resources".* FROM "resources" WHERE "resources"."id" = ? LIMIT 1 [["id", "35"]]
Rendered resources/show.html.erb within layouts/login (0.8ms)
Completed 200 OK in 93ms (Views: 90.5ms | ActiveRecord: 0.4ms)

如果有任何帮助,我将不胜感激。

最佳答案

Rails 通过值为 'put' 的参数 _method 确定 put 请求。

因为不是所有的浏览器都支持 put 方法,rails 在 form_tag 中作弊。它将此输出以 PUT 形式放置:

<input type='hidden' name='_method' value='put'>

所以你要做的是:

$.ajax({
type: "POST",
dataType: "script",
url: '/resources/35',
contentType: 'application/json',
data: JSON.stringify({ resource:{pos_y:45,pos_x:50}, _method:'put' })
}).done(function( msg )
{
alert( "Data Saved: " + msg );
});

关于javascript - Ruby on Rails - 更新 ajax 的 PUT 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11797270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com