【问题标题】:Jquery ajax and controller methodjQuery ajax 和控制器方法
【发布时间】: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 转换为对控制器中的 createupdate 操作的 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


【解决方案1】:

我是这样做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);
  });
});

在你的控制器中你应该用 JSON 响应

respond_to do |format|
  format.json { render json: @your_return_object }
end 

【讨论】:

    【解决方案2】:

    好像没问题。为什么浏览器没有任何反应?

    因为您尚未创建任何功能来处理响应。

    每当您发送 Ajax 请求时,您都会始终收到响应。此响应是您在编写 javascript 时需要考虑的。我会为你详细说明一个即时修复,然后是一个更系统的修复,它将让你走上一条更好的道路:


    Ajax

    根据您当前的设置,您需要使用以下方式接收数据:

    #app/assets/javascripts/application.js
    function ajaxsend() {
    
      $.ajax({
        url: "/articles",
        type: "POST",
        data: { "article": { "title": "acme", "text": "123 Carrot Street" } },
        success: function(resp){
           alert("Data");
        }
      });
    
    }
    

    在这种情况下,“警报”将产生您需要的效果。为了使这项工作正常工作,您必须使用自己的代码(我不知道您要实现什么目标)。

    还必须注意,您必须在 JS 中将此 ajax 代码与 事件 绑定:

    #app/assets/javascripts/application.js
    $(document).on("submit", "form", function() {
          $.ajax({
            url: $(this).attr("action"),
            type: "POST",
            data: $(this).serialize(),
            success: function(resp){
               alert("Data");
            }
          });
    });
    

    UJS

    对于 Rails,我们很幸运拥有Rails UJS 驱动程序,它为我们的 Rails 应用程序提供了一系列功能,我们可以隐式调用这些功能(IE 无需继续定义函数)。

    你可以看到Rails UJS Ajax functionality here

    具体来说,您可以这样做:

    #app/views/articles/new.html.erb
    <%= form_for @article, remote: true do |f| %>
    
    #app/controllers/articles_controller.rb
    class ArticlesController < ApplicationController
       respond_to :js, :json, :html
    
       def create
          @article = Article.new article_params
          @article.save
    
          respond_with @article
       end
    
       private
    
       def article_params
          params.require(:article).permit(:title, :text)
       end
    end
    
    #app/assets/javascripts/application.js
    $(document).on("ajax:success", "form", function(status, data, xhr){
       alert("DATA RECEIVED");
    });
    

    【讨论】:

    • 感谢@RichPeck!通过问题中的示例,我只是想弄清楚如何保存 json 对象。我有一个 javascript 工具来绘制图表,最终生成一个 json 对象,我想保存它。我没有表单,我只有一个需要保存在数据库中的 json。在这个简单的例子中,我试图弄清楚如何做到这一点,试图用 jquery ajax 保存一个简单的 json 对象(文章)。还有另一种方法可以做到这一点吗?我认为 UJS 的方式不符合我的要求,因为我没有表格。
    猜你喜欢
    • 1970-01-01
    • 2014-08-28
    • 2020-10-13
    • 2018-12-13
    • 2023-03-29
    • 1970-01-01
    • 2011-05-26
    • 2011-06-22
    • 1970-01-01
    相关资源
    最近更新 更多