【发布时间】:2014-09-14 00:08:19
【问题描述】:
我有这个控制器方法:
def create
render plain: params[:article].inspect
#@article = Article.new(article_params)
#@article = Article.create(article_params)
#if @article.save
# redirect_to @article
#else
# render 'new'
#end
end
还有这个 jquery ajax 请求:
function ajaxsend() {
$.ajax({
url: "/articles",
type: "POST",
data: { "article": { "title": "acme", "text": "text of the article" } },
success: function(resp){ }
});
}
但是在我单击运行 e jquery ajax 的按钮后,我什么也没得到。我期待渲染,但没有任何反应,甚至控制台中没有错误。 我究竟做错了什么?我不明白如何将 jquery ajax 的数据发送到控制器。 有什么帮助吗?我是 ruby on rails 开发的新手。红宝石版本:2.1.2;导轨版本:4.1.5;
编辑1:
效果很好,当我以传统方式以表格形式进行时:
结果:
编辑2:
当我按下按钮时,WEBrick 服务器会打印出来:
Started POST "/articles" for 127.0.0.1 at 2014-09-14 09:43:36 +0100
Processing by ArticlesController#create as */*
Parameters: {"article"=>{"title"=>"acme", "text"=>"123 Carrot Street"}}
Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.4ms | ActiveRecord: 0.0ms)
好像没问题。为什么浏览器没有任何反应?为什么 create 方法中的渲染不起作用?有什么帮助吗?
填写表格并按创建文章时的 WEBrick 响应:
Started POST "/articles" for 127.0.0.1 at 2014-09-14 09:52:21 +0100
Processing by ArticlesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"o8bzaGFcWGaHFFEbgZsfx5bWiHDAIaX3j4xXh3XkTwc=", "article"=>{"title"=>"mmmmm", "text"=>"mmmmm"}, "commit"=>"Create Article"}
Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.4ms | ActiveRecord: 0.0ms)
编辑3:
我也试过这种方式:
$.post("/articles", { "article": { "title": "Title1Ar", "text": "text of the article" } }, alert("callback"), "json").error(alert("error handler"));
WEBrick 中的这个:
Started POST "/articles" for 127.0.0.1 at 2014-09-15 09:19:49 +0100
Processing by ArticlesController#create as JSON
Parameters: {"article"=>{"title"=>"firsttitle", "text"=>"text of the article"}}
Rendered text template (0.0ms)
Completed 200 OK in 1ms (Views: 0.5ms | ActiveRecord: 0.0ms)
但在浏览器中也没有任何反应。 有什么帮助吗?
【问题讨论】:
-
您是否尝试在表单助手中添加
remote: true作为选项?这会将 POST 转换为对控制器中的create或update操作的 AJAX 请求。然后,您可以在articles视图文件夹中创建一个create.js.erb文件,它将运行该 JS。 -
我做了这个简单的表格只是为了了解我如何能够使用 jquery ajax 请求调用 que create 方法。因为我有一个用于绘制图表的javascript工具,但最后我想存储所有图表数据。我已经在 PHP 中完成了它,但现在我必须在 ruby on rails 应用程序中完成它。综上所述,我得把json对象存入服务器。
-
看起来它应该发送请求,尽管您不会在浏览器中看到任何响应。您提到在控制台中没有看到错误,您是指 Rails 控制台(假设您正在运行 WEBrick 服务器),还是浏览器中的 javascript 控制台? Firefox 中的 Firebug 对于调试这类事情是必不可少的。
-
你为什么说我在浏览器中看不到任何响应?我在服务器或浏览器控制台中都没有任何错误(是的,我正在运行 WEBrick 服务器)。有什么线索吗?
标签: jquery ruby-on-rails ruby ajax ruby-on-rails-4