简体   繁体   English

如何在Rails中响应Ajax调用

[英]How to respond to ajax call in Rails

I know there are many questions about that already on stackoverflow but none of them has been useful for me. 我知道关于stackoverflow的问题已经很多,但是没有一个对我有用。 Here is my ajax code: 这是我的ajax代码:

function update_schedule($task){
  var taskId = $task.data("taskId"),
    startHour, endHour,
    userId = $('#users').val();
  if( !$task.hasClass('daily-task')){ 
    startHour = getStartHour($task),
    endHour = startHour + (+$task.data('time'));
  }
  console.log(startHour, endHour)

   $.ajax({
          url: '/heimdall/update_scheduled_task',
          method: 'POST',
          data: { "task_id": taskId, "start_hour": startHour, "end_hour": endHour, "user_id": userId },
          success: function (){
            console.log("SUCESS!!", data['head'])
          },
          error: function () {
              console.log("FAILURE");
          },
          async: true
    }); 
}

The controller code: 控制器代码:

def update_scheduled_task
    scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
    scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id])

  end

I want to return the id of found or created task. 我想返回找到或创建的任务的ID。 I don't know how to send/receive this information. 我不知道如何发送/接收此信息。 I've read about respond to but still I don't know how to use it in this case. 我已经阅读了有关响应的信息,但在这种情况下我仍然不知道如何使用它。

You may do render json: ... to return the required info to ajax in JSON format: 您可以render json: ...以JSON格式将所需信息返回给ajax:

def update_scheduled_task
  scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
  scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id])

  render json: {scheduled_task_id: scheduled_task.id}
end

And in the ajax function's success, use it like: 在ajax函数成功的过程中,请像下面这样使用它:

success: function (data){
  var data = JSON.parse(data);

  console.log(data["scheduled_task_id"]);
},

First, you need to improve your controller code structure (You can rely on the default scaffold generator methods). 首先,您需要改善您的控制器代码结构(您可以依赖默认的脚手架生成器方法)。 Then, you must indicate that your method will respond to json format only, with the answer you want to return, something like this: 然后,您必须指出您的方法将仅响应json格式,并带有要返回的答案,如下所示:

def update_scheduled_task
  scheduled_task = ScheduledTask.find_or_create_by(task_id: params[:task_id])
  if (scheduled_task && scheduled_task.update_attributes(start_hour: params[:start_hour], end_hour: params[:end_hour], task_id: params[:task_id], user_id: params[:user_id]))
    render json: { scheduled_task_id: scheduled_task.id }
  else
    render json: { error: l18n.t("error.messages.request_error") }
  end
end

Then, you must modify the success and failure response methods of the jquery ajax request. 然后,您必须修改jquery ajax请求的成功和失败响应方法。 Here's an example of how it might look: 这是一个外观的示例:

$.ajax({
  url: "/heimdall/update_scheduled_task",
  method: "post",
  data: { task_id: taskId, start_hour: startHour, end_hour: endHour, user_id: userId },
  success: function(result) {
    if (result["scheduled_task_id"] != null) {
      console.log("Schedule record => " + result["scheduled_task_id"])
    } else {
      console.log("Error: " + result["error"])
    }
  },
  error: function() {
    console.log("Ajax request error");
  },
  // async: true => By default JQuery set true to async param.
});

Do not forget that you need to add a rule to access this method in the file config/ruotes.rb, something like this: 不要忘记,您需要在文件config / ruotes.rb中添加一条规则来访问此方法,如下所示:

post update_scheduled_task, :defaults => { :format => 'json' }

I hope this helped you, regards! 希望这对您有所帮助!

jQuery 's success and error callbacks rely on the status code returned by the controller. jQuerysuccesserror回调依赖于控制器返回的状态代码。 Make sure that you return the right status code when you are unable to create/read/update the object. 当您无法创建/读取/更新对象时,请确保返回正确的状态代码。 On success, simply render a JSON with the id property set. 成功后,只需渲染一个id属性设置为JSON的JSON。 I beleive update_attributes returns true on success: 我相信update_attributes成功返回true

if scheduled_task && scheduled_task.update_attributes(...)
  render json: { id: scheduled_task.id }
else
  head :unprocessable_entity
end

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

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