编码url并显示在iframe中

Encode url and show in iframe

本文关键字:iframe 显示 url 编码      更新时间:2023-09-26

我需要在自己的页面上显示iframe中的一些url。。。所以我写:

Route::get('/preview/{url}', 'ArticlesController@preview');

我的控制器功能:

public function preview($url) {
        $url = urlencode($url);
            return view('pages.preview', compact('url'));

    }

然后我的刀片预览页面(javascript):

function preview(){
    function autoResize(id){
    var newheight;
    var newwidth;
    if(document.getElementById){
        newheight = document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth = document.getElementById(id).contentWindow.document .body.scrollWidth;
    }
    document.getElementById(id).height = (newheight) + "px";
    document.getElementById(id).width = (newwidth) + "px";
};
    var content = '<iframe id="iframe2" src="{{$url}}" style="border:0px #FFFFFF none; position: relative;left: 0px;width: 100%; height:100%; top: 0;" name="myiFrame1" scrolling="yes" frameborder="0" marginheight="0px" marginwidth="0px" height="100%" width="100%" onLoad="autoResize(iframe1);"></iframe>';
var newNode = document.createElement("DIV");  
newNode.innerHTML = content;
document.body.appendChild(newNode); 

};
preview();

现在,当我尝试类似的东西时:

http://localhost:8888/preview/http%3A%2F%2Fwww.dubaimajestic.com%2F

http://localhost:8888/preview/http://www.dubaimajestic.com

我得到:

找不到此服务器上找不到请求的资源/预览/http%3A%2F%2Fwww.dubaimajestic.com%2F。

如何使其发挥作用?有什么想法吗?

这是因为http://www.dubaimajestic.com中有斜杠,无法正常使用laravel路由器。

您可以使用正则表达式约束来覆盖这种行为,如下所示:

Route::get('preview/{url}', 'ArticlesController@preview')->where('url', '(.*)');

这应该有效:

public function preview($url) {
    dd($url);
}

然而,我会换一种不同的方式,因为在我看来它有点干净:

Route::get('preview', 'ArticlesController@preview');

将您的url格式设置为:

http://localhost:8888/preview?url=http://www.dubaimajestic.com

你可以在你的控制器中这样阅读:

public function preview(Request $request) {
    dd($request->input('url'));
} 

/让Laravel认为这是路径的一部分。

我建议将URL设置为这样的查询字符串参数:

http://localhost:8888/preview?url=http://www.dubaimajestic.com

然后在你的routes.php:

// Don't accept {url} as an argument
Route::get('/preview', 'ArticlesController@preview');

然后在你的控制器中:

public function preview() 
{
    $url = request()->url;
    return view('pages.preview', compact('url'));
}

这应该行得通。