gpt4 book ai didi

ruby-on-rails - 为什么 Rails 3 中的 AJAX 如此困难?或者说,我做错了什么?

转载 作者:行者123 更新时间:2023-12-01 06:59:57 26 4
gpt4 key购买 nike

我似乎没有一个教程能完成我想做的事情。非常简单,我希望用户能够向 Controller 提交 POST 请求(“喜欢”视频)并让 Controller 使用 JSON 对象进行响应。任何帮助将不胜感激。

谢谢

编辑因为SO搞乱了格式,这也是我的代码的要点: https://gist.github.com/813503

这是我的 Controller :

class LikesController < ApplicationController

before_filter :get_ids

respond_to :json, :js

def videolink
results = {}

# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, @vid_id)

results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end

respond_with( results.to_json )
end


def update
results = {}

if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end

respond_with( results.to_json )
end


private

def get_ids
@vid_id = params[:videolink_id]
end

end

这是我的 JS 文件:

$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});

return false;
});

我的路线:

  resources :likes do
collection do
get "videolink"
end

member do
post :update
end
end

这是我得到的错误:



<h1>
NoMethodError
in LikesController#update
</h1>

undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>

最佳答案

如果你想发回自定义 JSON,而不是 respond_with(results.to_json)...只需渲染文本

render :text=>results.to_json

responds_with 是一种让您轻松发回对象及其位置 (url) 的方法。这就是为什么您的错误告诉您“_url”无效。

有关responds_with的更多信息,由http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering提供

If another format was requested, (i.e. :xml or :json)

  • If it was a GET request, invoke the :to_format method on the resource and send that back
  • If the resource has validation errors, send back the errors in the requested format with the :unprocessable_entity status code
  • If it was a POST request, invoke the :to_format method on the resource and send that back with the :created status and the :location of the new created resource
  • Else, send back the :ok response with no body

关于ruby-on-rails - 为什么 Rails 3 中的 AJAX 如此困难?或者说,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4914689/

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