5

在观看RailsCast #296 about Mercury Editor之后,我试图让编辑器重定向到新创建的资源。

我已经可以使用 JS 和window.location.href=. 但是对于一个新资源,我无法在客户端“猜测”它的 URL。我需要它在服务器响应中。

但是,问题是我看不到在编辑器中使用服务器响应的可能性。无论控制器呈现什么,Mercury 都会丢弃服务器响应,而不是将其用作我的函数的参数mercury:saved

有没有办法解决这个问题?

4

2 回答 2

7

通过发回有效的 JSON 字符串,我能够在更新时做到这一点。我会假设 create 以相同的方式工作。检查 firebug 以确保您在 Mercury 使用的 jQuery.ajax 调用中没有收到错误。

post_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) +'"}'
end

水银.js:

  jQuery(window).on('mercury:ready', function() {
    Mercury.on('saved', function() {
       window.location.href = arguments[1].url      
    });
  });

注意:我正在使用friendly_id来发布我的帖子

于 2013-01-28T16:38:10.127 回答
1

在服务器端重定向不起作用,因为保存按钮只是一个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 请求一样。作者在这里讨论了重写这个函数。通过将回调函数传递给save.

顺便说一句,做@corneliusk 建议的另一种方法是:

render { json: {url: post_path(post.slug)} }

无论哪种方式,响应主体都作为参数传递给mercury:saved回调中的函数。

于 2013-02-03T06:48:38.527 回答