我想通过ajax更新部分 View product_images.html.erb 我的js代码是
$("#delete-img").click(function(e){
var checkValues = $('input[name=image_id]:checked').map(function(){
return $(this).val();
}).get();
var id = $("#product_id").val();
if(checkValues.length == 0) {
alert("Select checkboxe first");
}
else{
$.ajax({
url: '/products/delete_product_images',
type: 'delete',
data: { ids: checkValues, id: id },
success:function(data){
$('.product_images_class').html("<%= escape_javascript(render 'sproduct_images')%>");
}
});
}
});
但它没有更新,而是写 <%= escape_javascript(render 'product_images')%>
成功后在那堂课上。
还有别的办法吗?
最佳答案
问题是因为您在前端 View 中调用服务器代码。
JS
当您调用 Ajax 时,您基本上是在使用前端 JS 向后端 Rails 架构发送异步请求。
这意味着您在前端 Ajax 中执行的任何操作都必须使用屏幕上的内容或服务器响应中发回的内容。
您正在做的是将前端ajax(IE $.ajax
)与后端ERB
混合 $('.product_images_class').html("<%= escape_javascript(render 'sproduct_images')%>");
的功能
有两种解决方法:
<强>1。调用服务端JS
第一个修复是使用 respond_to
functionality of Rails :
#app/controllers/products_controller.rb
class ProductsController < ApplicationController
def destroy
respond_to do |format|
format.js #-> invokes app/views/products/destroy.js.erb
end
end
end
这将有效地取代您的 success
前端ajax中的回调:
#app/views/products/destroy.js.erb
$('.product_images_class').html("<%=j render "product_images" %>");
#Front-end codr
$.ajax({
url: '/products/delete_product_images',
type: 'delete',
data: { ids: checkValues, id: id }
});
--
<强>2。将部分内容发送到前端 Ajax
#app/controllers/products_controller.rb
class ProductsController < ApplicationController
def destroy
if request.xhr? render "sproduct_images", layout: false
end
end
#Front-end code
$.ajax({
url: '/products/delete_product_images',
type: 'delete',
data: { ids: checkValues, id: id },
success: function(data) {
$('.product_images_class').html(data);
}
});
关于ruby-on-rails - 如何更新 ruby on Rails 中的部分 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33102963/