好的,在 PHP 中我可以在 5 分钟内完成此操作。对于 Rails,我完全迷失了。我对 Rails 很陌生,我需要用它做更高级的事情,然后我现在就感到舒服了。大佬决定放弃 PHP,放弃 Rails。所以这是速成类(class)的学习。有趣的时光..
我从 javascript 方面了解到,使用 jquery 进行 post/get 保持不变。然而,在 ruby 方面,我完全迷失了。我需要做什么才能发布/获取 Rails 应用程序。我将如何定义我的 Controller ?让我们从 HTML 方面说我正在发布
input1 和 input2 标准 jquery $.post 带有用于返回数据的 JSON 请求。使用 php 我会制作一个简单的 Controller ,例如:
public function myFormPostData(){
$errors = "none";
$errorMsg = "";
if($_POST['input1'] == ""){$errors = "found"; $errorMsg .= "Input 1 Empty<br>";}
if($_POST['input2'] == ""){$errors = "found"; $errorMsg .= "Input 2 Empty<br>";}
if($errors == "found"){ $output = array("error" => "found", "msg" => $errorMsg); }
else{
$output = array("error" => "none", "msg" => "Form Posted OK!!");
}
echo json_encode($output);
}
但在 ruby 中我不知道如何翻译这个概念。我愿意接受建议和良好做法。承认上面的内容是我需要做的事情的 super 平庸的表现,我会清理更多的东西,但它给出了我在 Rails 中寻找什么的想法..
最佳答案
首先,Rails 3 有一个很好的功能,称为 respond_with
。您可以查看有关此内容的 Railscast 剧集。 http://railscasts.com/episodes/224-controllers-in-rails-3 。如果您正在处理资源,他使用的示例非常有用。
话虽如此,我会给你一个更传统方法的例子。您需要有一个 Controller 操作来处理接受 JSON 响应的请求。
class MyController < ApplicationController
def foo
# Do stuff here...
respond_to do |format|
if no_errors? # check for error condition here
format.json { # This block will be called for JSON requests
render :json => {:error => "none", :msg => "Form Posted OK"}
}
else
format.json { # This block will be called for JSON requests
render :json => {:error => "found", :msg => "My bad"}
}
end
end
end
end
确保您已设置路线
post '/some/path' => "my#foo"
这些是您需要的基础知识。 Rails 为您免费提供了很多东西,因此您可能会发现您正在寻找的许多内容已经存在。
如果您发布一个更具体的示例来说明您正在尝试的内容,您可能会得到更好的建议。祝你好运!
关于jquery - Ruby On Rails jQuery AJAX 帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7588665/