【问题标题】:Codeigniter urls, doubled segment, like: news/news/Codeigniter url,双段,如:news/news/
【发布时间】:2012-03-31 14:18:42
【问题描述】:

我已经完成了 CI 文档中包含的众所周知的“新闻”教程。有时在我的链接字符串中出现双重“新闻/”段,如下所示:“/codeig/news/news/entry”,有时在重新加载页面后一切正常。我应该提到我已经摆脱了另一个流行教程之后的“index.php”部分。我的代码有什么问题?

这是我的路线:

$route['news/create'] = 'news/create'; 
$route['news/update/(:any)'] = 'news/update/$1';
$route['news/delete/(:any)'] = 'news/delete/$1';
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['welcome'] = 'welcome';

$route['auth/(:any)'] = 'auth/$1';
$route['auth'] = 'auth';
$route['activate/:num/:any'] = "/auth/activate/$1/$2";
$route['reset_password/:num/:any'] = "/auth/reset_password/$1/$2";

$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'news';

views/news/index.php 文件:

<?php foreach ($news as $news_item): ?>

<h2><?php echo $news_item['title'] ?></h2>
<div id="main">
    <?php echo $news_item['text'] ?>
</div>
<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

<?php endforeach ?>

查看方法(新闻控制器)

public function view($slug)
{
$data['news_item'] = $this->news_model->get_news($slug);

if (empty($data['news_item']))
{
    show_404();
}

$data['title'] = $data['news_item']['title'];

$this->load->view('templates/header', $data);
$this->load->view('news/view', $data);
$this->load->view('templates/footer');
}

【问题讨论】:

  • 我们无法判断您的代码有什么问题,因为您没有向我们展示任何内容...
  • 嗯,代码取自原始 CI 文档。
  • 你是如何构建输出双倍段的 URL 的,即news/news/?你能发布那个代码吗?
  • 我有同样的问题....我认为这是一个错字。我将&lt;a href="news/ 更改为&lt;a href="view/,一切正常

标签: php codeigniter url-routing


【解决方案1】:

在 HTML 中,如果当前 URL 是这样的:

http://example.com/news/

你有这样的链接:

<a href="news/article-slug">Link</a>

点击链接后,您的网址最终会是:

http://example.com/news/news/article-slug

如果你再次点击它,你会:

http://example.com/news/news/article-slug/news/article-slug

注意:这并不完全正确,路径的相对性确实取决于当前 URL 和/或您的链接中是否有尾部斜杠 /

href="news/something" 是一个relative URL,相对于当前页面。您想使用绝对 URL 或根 URL:

<a href="http://example.com/mysite/news/article-slug">Link</a>
<a href="/news/article-slug">Link</a>

使用以下任何 Codeigniter 函数来简化绝对 URL:

  • anchor()(为您制作整个链接)
  • site_url()(返回您的绝对基本 URL)
  • base_url()(同上)
<?php echo anchor('news/'.$news_item['slug'], 'Link Text'); ?>
<a href="<?php echo base_url('news/'.$news_item['slug']); ?>">Link Text</a>

所以澄清一下,这与您的路由无关 - 这纯粹是您的 HTML 中的相对链接的问题。

【讨论】:

  • 很好的答案 btw @Madmartigan 你现在在推特领域有了一个新的追随者:)
【解决方案2】:

一个不太详细的解释:

在文件'application/views/news/index.php'中

之前(在 URL 中导致 /news/news/):

<p><a href="news/<?php echo $news_item['slug'] ?>">View article</a></p>

之后(固定):

<p><a href="<?php echo $news_item['slug'] ?>">View article</a></p>

news/ 包含在 $news_item['slug'] 中,因此不需要在 HTML 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2014-11-23
    相关资源
    最近更新 更多