问题描述
我想使用下拉菜单更改英语和挪威语的语言.代码运行良好,但问题是它只能运行一次,每当我刷新页面语言时都会更改为英语.
I want to change language using dropdown for English and Norwegian.Code is working fine but issue is it is working for only one time, whenever I refresh page language is change to English.
查看页面.
<select class="form-control user_language">
<option value="en">English</option>
<option value="nl">Norwegian</option>
</select>
JS 代码.
<script>
$(".user_language").change(function(){
language=this.value;
$.ajax({
url:'<?=Yii::$app->request->baseUrl?>/site/changelanguage',
type:"GET",
data:{language:language},
success:function(result){
console.log(result);
location.reload();
},
});
});
</script>
控制器
public function actionChangelanguage()
{
if(isset($_REQUEST['language']) && $_REQUEST['language']!=null)
{
Yii::$app->language='nl';
echo Yii::$app->language;
die;
}
}
每次刷新页面时,我都检查过它是否工作一次,语言更改为英语.
I have checked that it working for one time whenever I refresh page, language is change to English.
如果我将 Yii::$app->language='nl';
放在每个页面中,它都可以工作,但我不想将此代码放在每个页面中.
If I put Yii::$app->language='nl';
in every page it is working but I don't want to put this code in every page.
推荐答案
Yii::$app->language
不是持久的 - 如果你在一个请求中设置它,它没有任何对进一步请求的影响.如果你想让设置语言持久化,你应该在 cookie 或 session 中保存值:
Yii::$app->language
is not persistent - if you set it in one request, it does not have any effect on further requests. If you want to make setting language persistent, you should save value in cookie or session:
Yii::$app->session->set('language', $_REQUEST['language'])
并添加到您的配置中:
'on beforeRequest' => function ($event) {
Yii::$app->language = Yii::$app->session->get('language', 'en');
},
如果用户尚未选择他的语言,这会将应用语言更改为 session 中的值或en".
This will change app language to value from session or 'en' if user does not chosen his language yet.
这篇关于在 Yii2 中更改语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!