2012-10-30 93 views
3

我有一個Javascript組件,當DOM被加載時,它需要發送一個請求到我們的CDN,其中可能位於不同的域中,以查看是否有內容這個組件。如果存在,組件將自行實例化(它是鏈接以打開模式中的嵌入式視頻),否則它會自毀。我的問題主要是關於我用來代理AJAX請求的Grails控制器。使用Grails控制器來代理AJAX請求

這裏是在僞代碼的JS:

checkForVideoAssets: function(videoDataUrl){ 
    Ajax.get(videoDataUrl, function(data){ 
    if(data.responseText==='error'){ 
    //tear down the component 
    } 
    else{ 
    //if there is data for the video instantiate the component 
    } 

這裏是Grails的控制器:

def checkForModalVideoAsset = { 
    def req = new URL("http://" + params.videoUrl + "/expense/videos/") 
    def connection = req.openConnection() 

    if(connection.responseCode != 200){ 
     render 'error' 
    } 

    if(connection.responseCode == 200){ 
     render req.getText() 
    } 
} 

所以,綜上所述,JS從具有一部分的DOM抓住一個屬性URL(我們通過約定定義),將該URL發送給控制器,控制器嘗試連接到該URL(在我們的CDN),然後將該響應傳遞迴XHR對象的responseText部分中的AJAX成功回調。這對我來說感覺不太理想,是否有可能將實際響應傳遞迴JS功能?

+1

此信息對您也可能有用:http://stackoverflow.com/a/2824968/311525 – Scott

回答

1

httpbuilder可能是有用的,以你

我從來沒有嘗試過,但類似的東西!?

def checkForModalVideoAsset = { 

    def http = new HTTPBuilder("http://" + params.videoUrl) 

    http.get( 
      path : "/expense/videos/", 
      contentType : TEXT) { resp, reader -> 
      response.properties=resp.properties //<-- to easy to work but why not try :) 
      response << resp 
      } 
    }