繁体   English   中英

如何在Rails中响应Ajax调用

[英]How to respond to ajax call in Rails

我知道关于stackoverflow的问题已经很多,但是没有一个对我有用。 这是我的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
    }); 
}

控制器代码:

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

我想返回找到或创建的任务的ID。 我不知道如何发送/接收此信息。 我已经阅读了有关响应的信息,但在这种情况下我仍然不知道如何使用它。

您可以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

在ajax函数成功的过程中,请像下面这样使用它:

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

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

首先,您需要改善您的控制器代码结构(您可以依赖默认的脚手架生成器方法)。 然后,您必须指出您的方法将仅响应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

然后,您必须修改jquery ajax请求的成功和失败响应方法。 这是一个外观的示例:

$.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.
});

不要忘记,您需要在文件config / ruotes.rb中添加一条规则来访问此方法,如下所示:

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

希望这对您有所帮助!

jQuerysuccesserror回调依赖于控制器返回的状态代码。 当您无法创建/读取/更新对象时,请确保返回正确的状态代码。 成功后,只需渲染一个id属性设置为JSON的JSON。 我相信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