假设我的网站中有这些网址
http://www.example.com/locations
http://www.example.com/locations/sydney
http://www.example.com/locations/brisbane
http://www.example.com/locations/perth
http://www.example.com/services/
http://www.example.com/services/cars
http://www.example.com/services/truck
http://www.example.com/services/phone
http://www.example.com/blog/display/blog-title
http://www.example.com/blog/display/blog-title2
http://www.example.com/blog/display/blog-title3
http://www.example.com/blog/display/blog-title4
我想要的是这样的网址
http://www.example.com/locations
http://www.example.com/brisbane
http://www.example.com/services/
http://www.example.com/blog-title
http://www.example.com/blog-title2
http://www.example.com/blog-title3
http://www.example.com/blog-title4
如何在codeigniter中实现这一目标?
我尝试了以下代码:
$route[''] = 'blog/index';
$route['(:num)'] = 'blog/index/$1';
$route['(:any)'] = 'blog/display/$1';
$route['home/(:any)'] = 'blog/display/$1';
但是问题是,仅适用于博客的内容不能用于其他人的相同代码,这会使其他链接被破坏
所以我尝试了@ACD回答它给了2个错误 1.未定义的属性:CI_Router :: $ load 2.在null上调用成员函数library()
所以我做了这样的修改
$req = $this->uri->segment(1);
require_once ( BASEPATH. 'database/DB.php');
$db =& DB();
if ($db->get_where('home_inner_tbl', array('page_url' => $req))) {
$route['(:any)'] = 'home/display/$1';
} elseif ($db->get_where('blog_tbl', array('page_url' => $req))) {
$route['(:any)'] = 'blog/blog_display/$1';
} elseif ($db->get_where('towing_services_tbl', array('page_url' => $req))) {
$route['(:any)'] = 'towing-services/display/$1';
} elseif ($db->get_where('special_services_tbl', array('page_url' => $req))) {
$route['(:any)'] = 'cash-for-cars/display/$1';
} elseif ($db->get_where('locations_tbl', array('page_url' => $req))) {
$route['(:any)'] = 'locations/display/$1';
}
使用此代码,它没有给出错误,而只是if语句的第一行起作用,即$ route ['(:any)'] ='home / display / $ 1'; locatins,拖车服务,博客,汽车现金等其他链接无效。
if语句有问题吗?因为看起来这个答案应该是正确的。
通过我的控制器看起来像这样
class Home extends CI_Controller
{
public function index() {
// some code in here
}
public function display($page_url) {
// some code in here
}
}
外观相仿的控制器会传给其他人(位置,博客,towing_services等)
如您所见,我正在从数据库中调用$ page_url。
任何人都可以帮助我吗?谢谢
答案 0 :(得分:0)
您可以先过滤掉要创建的路由,然后再创建路由(如果该请求存在),假设可以在数据库中提取url请求(或将其更改为您要知道的某种类别的度量): / p>
$req = $this->uri->segment(1);
if ($this->db->get_where('locations_table', array('name' => $req))) {
$route['(:any)'] = 'locations/$1';
} else if ($this->db->get_where('blogs_table', array('name' => $req))) {
$route['(:any)'] = 'blog/display/$1';
} else if ($this->db->get_where('services_table', array('name' => $req))) {
$route['(:any)'] = 'services/$1';
}
仅供参考:除非每个类别都有特定的格式,否则htaccess无法完成此操作(例如:位置-loc_singapore,loc_usa;服务-svc_someservice等)