You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CodeIgniter 4、PHP、JS获取浏览器请求URL并显示?

使用CodeIgniter 4、PHP和JavaScript获取并显示请求URL

一、通过CodeIgniter 4(PHP后端)获取请求URL

CodeIgniter 4内置请求对象,可轻松获取当前请求的URL,步骤如下:

1. 控制器中获取URL

在控制器文件(例如App/Controllers/Home.php)中,注入Request接口并获取URL:

<?php

namespace App\Controllers;

use CodeIgniter\Controller;
use CodeIgniter\HTTP\RequestInterface;

class Home extends Controller
{
    public function index(RequestInterface $request)
    {
        // 获取不含域名的请求路径
        $requestPath = $request->getUri()->getUriString();
        // 获取包含完整域名的URL
        $fullRequestUrl = base_url($requestPath);
        
        // 将URL传递到视图
        return view('welcome', ['requestUrl' => $fullRequestUrl]);
    }
}

2. 视图中显示URL

在对应的视图文件(例如App/Views/welcome.php)中输出URL:

<p>后端获取的请求URL:*<?= esc($requestUrl) ?>*</p>

二、通过JavaScript获取前端页面URL

如果需要直接在浏览器端获取当前页面的URL,使用原生JavaScript即可:

<p>前端获取的页面URL:<span id="url-display"></span></p>

<script>
// 获取完整页面URL
const currentUrl = window.location.href;
// 仅获取路径部分可使用 window.location.pathname

// 将URL显示到页面
document.getElementById('url-display').textContent = currentUrl;
</script>

三、整合后端与前端方案

如果需要同时展示两种方式获取的URL,直接将上述代码整合到视图中:

<p>后端请求URL:*<?= esc($requestUrl) ?>*</p>
<p>前端页面URL:<span id="js-url"></span></p>

<script>
document.getElementById('js-url').textContent = window.location.href;
</script>

内容的提问来源于stack exchange,提问作者mehmetsar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:42:24