我有这个 Controller 方法:
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 数据发送到 Controller 。 有什么帮助吗?我是 ruby on rails 开发的新手。 ruby 版本:2.1.2; rails 版本: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)
但是浏览器中没有任何反应。 有帮助吗?
最佳答案
我是这样调用ajax的,你可以试试:
$("#test-ajax-controller").on("click", function() {
request = void 0;
request = $.ajax({
url: "/articles/create/?title=acme&text=123 Carrot Street"
});
request.done(function(data, textStatus, jqXHR) {
console.log(data);
});
request.error(function(jqXHR, textStatus, errorThrown) {
alert("AJAX Error:" + textStatus);
});
});
并且在您的 Controller 中您应该以 JSON 格式响应
respond_to do |format|
format.json { render json: @your_return_object }
end
关于Jquery ajax 和 Controller 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828909/