2012-07-17 30 views
4

看完RailsCast #296 about Mercury Editor後,我試圖讓編輯器重定向到一個新創建的資源。如何讓Mercury Editor重定向到新資源?

我已經可以在客戶端使用JS和window.location.href=重定向。但是對於一個新的資源,我不能在客戶端「猜測」它的URL。我需要它在服務器響應。

但是,問題是我沒有看到在編輯器中使用服務器響應的可能性。無論控制器如何渲染,服務器的響應是由水星製作的discarded,而不是作爲我的函數的參數,用於mercury:saved

有沒有辦法解決這個問題?

回答

7

我可以通過發回一個有效的JSON字符串來做到這一點。我會假設創建工作方式相同。檢查firebug以確保你沒有在Mercury使用的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) +'"}' 
end 

mercury.js:

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

注:我使用friendly_id段塞我的職位,在服務器端,因爲不工作

+0

我想你的意思是'參數[1] .url'上面。 – jordanpg 2013-02-03 06:04:38

+2

@jordanpg,我想你的意思是'render:json => {:url => post_path(post.slug)}' – corneliusk 2013-02-04 15:24:10

+0

@ awendt-似乎這個答案對人有用,你認爲你能接受嗎? – corneliusk 2014-02-10 18:43:35

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請求一樣。作者討論重寫這個非常功能here。它也看起來像通過回調函數save可能有一些機動。

順便說一句,另一種方法做什麼建議是@corneliusk:

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

無論哪種方式,響應體被作爲參數傳遞給在mercury:saved回調函數傳遞。