我有一个 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 函数?