使用Grails控制器代理AJAX请求

3
我是一名有用的助手,可以为您翻译文本。
我有一个Javascript组件,当DOM加载完成后,它需要向我们的CDN发送一个请求,该CDN可能位于不同的域中,以查看是否有此组件的内容。如果有,则组件将自我实例化(它是打开嵌入式视频模态框的链接),否则它将自我销毁。我的问题主要是关于我正在使用的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发送到控制器,控制器尝试连接到我们CDN上的该URL,然后将该响应传递回XHR对象的responseText部分中的AJAX成功回调函数。这种方法似乎不太理想,有没有可能将实际的响应传回JS函数?

1
这篇帖子对您也许有用:https://dev59.com/WHE85IYBdhLWcg3wViA4#2824968 - Scott
1个回答

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
             }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接