Yii框架url美化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014607184/article/details/82391919

url美化

目的:

http://localtest/yii/web/index.php?r=hello/index

美化成:

http://localtest/yii/web/hello/index

这里我是用的wampserver新建了一个localtest站点(详情可点击这里点击这里),并将yii的basic文件夹重新命名为yii。

对比上面的两个地址,其实就是把index.php?r=隐藏。

这里分两步:

1、增加.htaccess文件

在web根目录下增加.htaccess文件,内容为:

RewriteEngine on

 # 如果是一个目录或者文件,就访问目录或文件
 RewriteCond %{REQUEST_FILENAME} !-d

 # 如果文件存在,就直接访问文件,不进行下面的RewriteRule
 RewriteCond %{REQUEST_FILENAME} !-f

 RewriteRule . Index.php

无法直接创建.htaccess,可以先创建一个txt文件,然后另存为…,保存为文件名为.htaccess,保存类型选择所有文件即可。

2、配置config/web.php

在config/web.php中的components数组中增加这一项:

'urlManager' => [
            // //开启url美化
            'enablePrettyUrl' => true,
            // //隐藏index.php
            'showScriptName' => false,
            // //禁用严格匹配模式
            'enableStrictParsing' => false,
            // //url后缀名称
            // 'suffix'=>'.html',
            'rules' => [
            ],
        ],

这时,可以将URL中的index.php?r=删除,如果出现404报错,可以查看服务器的配置,我用的是wampsever中集成的apache,需要检查一下配置:

扫描二维码关注公众号,回复: 3337471 查看本文章

conf\httpd.conf中,开启 apache 的 mod_rewrite 模块
去掉LoadModule rewrite_module modules/mod_rewrite.so前的“#”符号;

然后修改 apache 的 AllowOverride
将 AllowOverride None 修改为 AllowOverride All;

由于我是在conf\extra\httpd-vhosts.conf中配置了站点,所以需要同步去httpd-vhosts.conf中将对应站点的AllowOverride None 修改为 AllowOverride All;

至此,我就可以用http://localtest/yii/web/hello/index
来访问http://localtest/yii/web/index.php?r=hello/index

适配ajax请求路径

由于我用Yii框架主要进行一些服务端的逻辑处理,例如接口以及session管理等,由于要做到前后端分离,Yii主要还是给前端提供API。这里我先写一个简单的例子测试一下上面美化之后的url是否适用于我们常用的ajax。

先在web目录下新建了一个index.html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>text</title>
</head>
<body>
    <h1>test</h1>
</body>
<script type="text/javascript" src="lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(function(){
    $.ajax(
            {
                type : 'GET',
                url : 'hello/resp',
                data: {
                    age: 12,
                    name: 'sean'
                },
                success : function(response){
                    console.log(JSON.parse(response) );

                }
            });
});
</script>
</html>

为了方便,这里我就直接引用了jquery封装好的ajax方法,可以注意到,我这里用的url : ‘hello/resp’。

对应的在HelloController中加了这么个方法:

public function actionResp(Type $var = null)
    {
        $request =  Yii::$app->request;
        $age = $request->get('age');
        $name = $request->get('name');

        $arr = array('age' =>$age , 'name'=>$name);
        $response = json_encode($arr);
        return $response;
    }

在浏览器中,可以得到正确的返回值:
这里写图片描述

可以注意到url的地址为http://localtest/yii/web/hello/resp,这其实就是我们上面美化后的地址。

为了进一步测试相对路径的问题,我们在web下新建了一个test文件夹,并在其中新增了一个test.html文件:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>text</title>
</head>

<body>
    <h1>test</h1>
</body>
<script type="text/javascript" src="../lib/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
    $(function () {
        $.ajax(
            {
                type: 'GET',
                url: 'hello/resp',
                data: {
                    age: 12,
                    name: 'sean'
                },
                success: function (response) {
                    console.log(JSON.parse(response));

                }
            });
    });
</script>

</html>

内容与index.html一致(jquery路径做对应的变化),浏览器中访问后,ajax请求报404:
这里写图片描述

可以注意到,此时ajax请求的地址为http://localtest/yii/web/test/hello/resp的,请求是在web/test下,不是之前的web/目录,稍微变通一下,修改一下url: '../hello/resp',再次访问就可以了。

至此我们基本上可以知道了,通过我们的URL美化,我们可以将发送到web/下的请求,转发到index.php中,所以需要保证我们的请求发送到了web目录下。但是,如果按照上述的方法,每一个ajax请求都手动去计算和更改对应的url肯定是不合理的,因此可以封装一个公共方法。

如果我们的前端代码都是放在web目录下,那么可以在web下新建一个公共js文件,里面写一个获取web路径方法即可:

function getLocalUrl() {
        var url = '';
        var str =  window.location.href;
        try{
            url =  str.split('web/')[0] + 'web/';
        }catch(e){

        }
        return url;
    }

这样,上述的test.html文件可以引入这个方法,url的方法就可以改写成:

url: getLocalUrl() + 'hello/resp',

这样,每次调用的时,直接调用getLocalUrl()方法即可,不需要在人为计算路径。

同理,如果如果前端代码和后端php代码分开不同路径部署,也可以根据自己具体的项目路径来获取到web路径。

猜你喜欢

转载自blog.csdn.net/u014607184/article/details/82391919