gpt4 book ai didi

jquery - 在 Rails 4 中处理 AJAX 调用(成功、错误、发送前、完成)

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:19 26 4
gpt4 key购买 nike

我想知道在 Rails 4 中处理 ajax 调用的正确方法是什么(当使用 remote: true 选项时),问题是我想在处理过程中使用所有经典步骤,例如成功,错误,发送前完成。

假设我有这个按钮,它会加载一个带有一些 ajax 的模态窗口:

查看(产品/索引):

<%= link_to('Order this', new_order_path(product: product), remote: true) %> 

订单 Controller :

  def new
@order = Order.new
@product = Product.find(params[:product])

respond_to do |format|
format.html
format.js
end
end

新的.js.erb:

(function(){
var $modalWindow = ...
// some code that loads the modal window and closes it

$modalWindow.html("<%= j render('form') %>"); // puts the needed product form
into my modal window
}());

这工作正常,但是在此代码中之前/之后/成功/错误在哪里?

接下来,当“订购产品”按钮被点击时,我的订单 Controller 中有这个:

def create
@product = Product.find_by(params[:id])
@order = current_office.orders.build(order_params)

respond_to do |format|
if @order.save

format.html {
flash[:success] = 'Order created'
redirect_to products_url
}
format.js
else
render :new
format.html { render :new }
format.js { render :js=>'alert("ajax error");' }
end
end
end

同样,单击“创建”按钮后,我该如何进行处理?我的 create.js.erb 只关闭模态窗口,但我希望它能够完全处理请求,在发送前显示预加载器,然后是成功/错误,然后是发送后。

希望不要太乱!

最佳答案

where does the before/after/success/error go in this code?

ajax 事件 不属于该代码 - 因为它们不能绑定(bind)到原始 DOM 元素。您需要将它们放在原始 JS 中 - 因为只有这样才能将元素绑定(bind)到发送请求的 DOM 元素:

#app/assets/javascripts/application.js
$(document).on("ajax:success", "#element", function() {
//do something
});

这里有一个很好的资源:rails3 rails.js and jquery catching success and failure of ajax requests


后端

如果您要在后端处理处理代码,则需要使用某种验证来确定应该发生什么:

 #app/controllers/orders_controller.rb
def new
@order = Order.new
@product = Product.find(params[:product])

respond_to do |format|
format.html
format.js { @state = "success" }
end
end

#app/views/orders/new.js.erb
(function(){
<% if @state && @state == "success" %>
var $modalWindow = ...
$modalWindow.html("<%= j render('form') %>");
<% else %>
alert ("not successful");
<% end %>
}());

前端

如果你想在前端处理ajax请求,你最好做这样的事情:

#app/assets/javascripts/application.js
$(document).on("ajax:success", "#element", function(){
//do something
});

插件

我还没有这方面的任何文档:

(function( $ ){        

$.fn.leanModal = function(options) {

//Defaults
var defaults = {
overlay: 0.5,
overlay_color: "#000",
closeButton: null,
delay: null,
drag: ".modal_title",
removeModal: null,
autoLoad: null,
ajax: false
};

//Definitions
var xhr;
var plugin = this;
var options = $.extend(defaults, options);

//Init
plugin.init = function() {

if(options.autoLoad){
$.extend(options, {modal_id: $(this)});
create();
}else{
return this.each(function() {
$(this).click(function(e) {
e.preventDefault();
var href = $(this).attr("href");
var image = CheckImg(href);

var random = Math.floor(Math.random()*90000) + 10000;
var extras = (options.ajax || image) ? {modal_id: "#modal_" + random, ajax: href.replace(/\/$/, '')} : {modal_id: href};

$.extend(options, extras);
create();
});
});
}
}

//////////////////
// Actions //
//////////////////

//Build
var create = function() {
if(options.ajax){

//Loading
load();

//Image
switch (true) {
case CheckImg(options.ajax):
append("img", options.modal_id.substring(1), options.ajax);
show();
break;
default:
fetch(options.ajax, function(data){
append("modal", options.modal_id.substring(1), options.ajax, data);
show();
}, function(xhr, text_status, error_thrown){
load();
alert("Sorry, there was an error!");
});
break;
}

}else{
show();
}
}

//Ajax
var fetch = function(link, success, error) {
xhr =
$.ajax({
url: link,
success: function(data) { success(data); },
error: function(data) { error(data); }
});
}

//Overlay
var olay = function(modal_id, removeModal, closeButton, ajax) {
var overlay = document.createElement("div");
overlay.setAttribute("id", "lean_overlay");

document.body.appendChild(overlay);
overlay.onclick = function() { close(modal_id, removeModal, $(closeButton), ajax); return false; };
}

//Show
var show = function() {

/* Vars */
var id = options.modal_id
var removeModal = options.removeModal
var closeButton = options.closeButton
var drag = options.drag
var ajax = options.ajax
var opacity = options.overlay

/* Overlay */
olay(id, removeModal, closeButton, ajax);

/* Elements */
var modal = $(id);
var overlay = $("#lean_overlay");

/* Display */
var disp = "test";

/* Options */
if (closeButton) {
$(closeButton).css("z-index", "900");
$(closeButton).on("click", function (e) {
e.preventDefault();
close(id, removeModal, $(closeButton));
return false;
});
}

/* Load */
if (ajax) {
modal.waitUntilExists(function() {
load();
display($("#lean_overlay"), options.overlay_color, $(options.modal_id), options.overlay, options.drag);
})
} else { display($("#lean_overlay"), options.overlay_color, $(options.modal_id), options.modal, options.overlay, options.drag); }
}

//Close
var close = function(modal, removeModal, closeButton, ajax) {

/* Ajax */
if(ajax){
if (xhr) { xhr.abort(); }
load(true);
}

/* Overlay */
$("#lean_overlay").fadeOut(150, function(){
$(this).remove();
if(closeButton) {
closeButton.off("click");
closeButton.removeAttr('style');
}
});

/* Modal */
$(modal).fadeOut(150, function(){
if (removeModal) {
$(this).remove();
}
});

}

//Go
plugin.init();
};


//////////////////
// Dependencies //
//////////////////

//Image?
var CheckImg = function(url) { if(url) { return(url.match(/\.(jpeg|jpg|gif|png)/) != null); }}

//Create
var append = function(type, id, src, data) {

//Definitions
var style = element = type;

if (type == "modal") {
var style = "ajax";
var element = "div";
}

//Element
var el = document.createElement(element);
el.setAttribute("id", id);
el.setAttribute("src", src);
el.className = 'modal ' + style;

//Ajax
if (data) { el.innerHTML = data; }

//Append
document.body.appendChild(el);
}

//Show
var display = function(overlay, overlay_color, modal, opacity, drag) {

/* Styling */
overlay.css({
"display": "block",
"background": overlay_color,
opacity: 0
});
modal.css({
"display": "block",
"position": "fixed",
"opacity": 0,
"z-index": 10200,
"left": 0,
"right": 0,
"top": 0,
"bottom": 0,
"margin": "auto"
});

/* Init */
overlay.fadeTo(150, opacity);
modal.fadeTo(200, 1);
if(drag.length > 0) { modal.draggable({ handle: drag }); }

}

//Ajax Load
var load = function(close) {
if (close) { $(document).ajax_load({close: true}); } else { $(document).ajax_load(); }
}

})( jQuery );

用法

#app/assets/javascripts/application.js
var load = function() {
$('a[rel*=LeanModal]').leanModal({
overlay: 0.9,
removeModal: true,
closeButton: ".title .close"
ajax: true,
drag: ".title"
});
}
$(document).on("ready page:load", load);

#app/assets/sytlesheets/application.css.sass
/Overlay
#lean_overlay
position: fixed
z-index: 1500
top: 0px
left: 0px
height: 100%
width: 100%
display: none

&:hover
cursor: pointer

// Modal
.modal
//styling here


#app/views/application/index.html.erb
<%= link_to "test_ajax", ajax_path, rel: "LeanModal" %>

#app/controllers/application_controller.rb
layout Proc.new {|controller| controller.request.xhr? ? false : "application" }

关于jquery - 在 Rails 4 中处理 AJAX 调用(成功、错误、发送前、完成),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22729733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com