![](/img/trans.png)
[英]Rails 5: Respond to AJAX call with HTML (instead of javascript)
[英]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' }
希望這對您有所幫助!
jQuery的success
和error
回調依賴於控制器返回的狀態代碼。 當您無法創建/讀取/更新對象時,請確保返回正確的狀態代碼。 成功后,只需渲染一個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.