【问题标题】:Use Grails Controller to proxy an AJAX request使用 Grails Controller 代理 AJAX 请求
【发布时间】:2012-10-30 16:42:55
【问题描述】:

我有一个 Javascript 组件,当加载 DOM 时,它需要向我们的 CDN(可能在不同的域中)发送请求,以查看该组件是否有内容。如果有,该组件将自实例化(它是一个在模态中打开嵌入视频的链接),如果没有,它将自毁。我的问题主要是关于我用来代理 AJAX 请求的 Grails 控制器。

这是伪代码中的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 函数?

【问题讨论】:

标签: ajax grails cross-domain


【解决方案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
             }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 2012-05-12
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多