看完RailsCast #296 about Mercury Editor之后,我尝试让编辑器重定向到新创建的资源。
我已经可以使用JS和window.location.href=在客户端进行重定向。但是对于一个新的资源,我不能在客户端“猜测”它的URL。我需要它出现在服务器响应中。
然而,问题是我看不到在编辑器中使用服务器响应的可能性。无论控制器呈现什么,服务器响应都是Mercury的discarded,而不是用作我的mercury:saved函数的参数。
有没有办法绕过这个问题?
发布于 2013-01-29 00:38:10
我可以在更新时通过发回一个有效的JSON字符串来做到这一点。我假设create以同样的方式工作。检查firebug以确保在水星使用的jQuery.ajax调用中没有收到错误。
posts_controller.rb
def mercury_update
post = Post.find(params[:id])
post.title = params[:content][:post_title][:value]
post.body = params[:content][:post_body][:value]
post.save!
render text: '{"url":"'+ post_path(post.slug) +'"}'
endmercury.js:
jQuery(window).on('mercury:ready', function() {
Mercury.on('saved', function() {
window.location.href = arguments[1].url
});
});注意:我正在使用friendly_id来攻击我的帖子
发布于 2013-02-03 14:48:39
服务器端的重定向不起作用,因为保存按钮只是一个jQuery.ajax调用:
// page_editor.js
PageEditor.prototype.save = function(callback) {
var data, method, options, url, _ref, _ref1,
_this = this;
url = (_ref = (_ref1 = this.saveUrl) != null ? _ref1 : Mercury.saveUrl) != null ? _ref : this.iframeSrc();
data = this.serialize();
data = {
content: data
};
if (this.options.saveMethod === 'POST') {
method = 'POST';
} else {
method = 'PUT';
data['_method'] = method;
}
Mercury.log('saving', data);
options = {
headers: Mercury.ajaxHeaders(),
type: method,
dataType: this.options.saveDataType,
data: data,
success: function(response) {
Mercury.changes = false;
Mercury.trigger('saved', response);
if (typeof callback === 'function') {
return callback();
}
},
error: function(response) {
Mercury.trigger('save_failed', response);
return Mercury.notify('Mercury was unable to save to the url: %s', url);
}
};
if (this.options.saveStyle !== 'form') {
options['data'] = jQuery.toJSON(data);
options['contentType'] = 'application/json';
}
return jQuery.ajax(url, options);
};因此,您的重定向被发送到success回调函数,但是页面并不像任何成功的AJAX请求那样实际重新呈现。作者讨论了重写这个函数here。通过将回调函数传递给save,看起来这里可能还有一些回调空间。
顺便说一句,@corneliusk建议的另一种方法是:
render { json: {url: post_path(post.slug)} }无论采用哪种方法,响应体都会作为参数传递给mercury:saved回调中的函数。
https://stackoverflow.com/questions/11525665
复制相似问题