简体   繁体   English

AJAX和Rails:发布到控制器失败

[英]AJAX and Rails: Post to Controller failing

I have a Rails model that has a simple boolean attribute. 我有一个具有简单布尔属性的Rails模型。 I am trying to update that attribute in the background when a user clicks a checkbox in a view. 当用户单击视图中的复选框时,我正在尝试在后台更新该属性。 I believe that I have configured the AJAX and controller/router correctly, but when I do press a button, the error function for the AJAX post fires, rather than the success one. 我相信我已经正确配置了AJAX和控制器/路由器,但是当我按下一个按钮时,会触发AJAX帖子的错误功能,而不是成功的错误功能。

I am not really sure where to go from here, there isn't really any useful information I can extract from the error. 我不太确定从哪里可以去,我实际上没有任何可以从错误中提取的有用信息。

config/routes.db config / routes.db

...
post "/task_toggle" => "tasks#toggle", :as => "task_toggle"
...

The tasks_controller does exist and has a method toggle. task_controller确实存在并且具有方法切换。

This is the javascript at the end of the body. 这是正文末尾的javascript。 I am using taskNumber to get the ID for the model that needs to be toggled, and I have confirmed that it is indeed correct. 我正在使用taskNumber来获取需要切换的模型的ID,并且我已经确认它是正确的。

JavaScript/AJAX 的JavaScript / AJAX

<script type="text/javascript">
    $(document).on("click", ".check-task-btn", function() {

        var taskNumber = $(this).parent().attr("id").substring(4);

        $.ajax({
            url: "/task_toggle",
            type: "post",
            data: {task_id: taskNumber},
            dataType: "JSON",
            success: function() {
               window.alert("it worked");
            },
            error: function() {
                window.alert("no");
            }
        });
    });
</script>

When I press a checkbox that is marked with the check-task-btn class I get the message no printed. 当我按下标有check-task-btn类的复选框时,我得到的消息未打印。

Here is the controller just in case there is something noteworthy in here. 这是控制器,以防万一在这里值得注意。

TasksController TasksController

def toggle
    task = Task.find(params[:task_id])
    task.finished = !task.finished
    task.save
    redirect_to root_path
end

Does anybody have any idea why my AJAX is failing? 有人知道我的AJAX为什么会失败吗?

Thank you 谢谢

EDIT: So I just checked and it is actually applying changes to the DB, but I am still getting the alert printed from the error. 编辑:所以我只是检查了一下,它实际上是在对数据库应用更改,但是我仍然从错误中打印警报。 Why would that be? 为什么会这样呢?

Further to @vinodadhikary's answer, the most likely problem is that your controller is not rendering the view correctly. 除了@vinodadhikary的答案,最可能的问题是您的控制器无法正确呈现视图。 I wanted to write an answer because I think you'll benefit from the " Network " tab of the developer tools part of Chrome / Firefox 我想写一个答案,因为我认为您将从Chrome / Firefox的开发人员工具部分的“ 网络 ”标签中受益


Chrome Developer Tools Chrome开发人员工具

When you send an Ajax call, your system is basically performing an HTTP request on your behalf (with JS). 当您发送Ajax调用时,您的系统基本上是代表您(使用JS)执行HTTP请求。 In simple terms, your browser is essentially loading a URL without refreshing your page 简单来说,您的浏览器实际上是在加载URL而不刷新页面

Most people don't understand this, and presume AJAX is some mysterious technology. 大多数人不了解这一点,并且认为AJAX是一种神秘的技术。 The reality is that the error you're getting is going to be the result of Rails having an error in the backend. 现实情况是,您得到的错误将是Rails在后端出现错误的结果。 To see what error, you just need to do this: 要查看什么错误,您只需要执行以下操作:

  • Right-click & select "Inspect Element" 右键单击并选择“检查元素”
  • In the tab which loads, select "Network" 在加载的标签中,选择“网络”
  • In the network tab, scroll down the left & find the Ajax request (will be in red at the bottom) 在“网络”标签中,向下滚动并找到Ajax请求(底部将显示为红色)
  • Click it & load the "preview" sub-tab 单击它并加载“预览”子选项卡
  • This should show the Rails error for the request 这应该显示请求的Rails错误

Controller Response 控制器响应

As mentioned by @vinodadhikary, the controller's response is likely the cause of the issue. 如@vinodadhikary所述,控制器的响应很可能是造成此问题的原因。 The reason is because the respond_to tag is absent 原因是因为没有respond_to标记

respond_to allows your controller actions to handle different mime-types (JS / JSON / HTML) in different ways. respond_to允许您的控制器操作以不同方式处理不同的mime类型 (JS / JSON / HTML)。 You're currently blanketing all your requests like this: 您目前正在按以下方式处理所有请求:

def toggle
    task = Task.find(params[:task_id])
    task.finished = !task.finished
    task.save
    redirect_to root_path
end

This will handle every request in the same way (redirect to the root_path), but if you're sending a JSON or JS request, you'll be much better placed to handle the requests differently, like @vinodadhikary's answer: 这将以相同的方式(重定向到root_path)处理每个请求,但是如果您要发送JSON或JS请求,则可以更好地以不同方式处理请求,例如@vinodadhikary的答案:

def toggle
    task = Task.find(params[:task_id])
    task.finished = !task.finished
    task.save
    repsond_to do |format|
       format.html { redirect_to root_path }
       format.json
    end
end 

I believe the culprit is the redirect_to root_path here. 我相信罪魁祸首是这里的redirect_to root_path Try responding to different formats as you've asked for json format in your ajax call. 尝试响应不同的格式,就像在ajax调用中要求json格式一样。

Give this a try: 试试看:

  def toggle
    task = Task.find(params[:task_id])
    task.finished = !task.finished

    if task.save
      respond_to do |format|
        format.html { redirect_to root_path }
        format.json 
      end
    else
      # return an error here accordingly
    end
  end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM