如何使用i18next从PHP加载资源?

时间:2019-03-24 12:59:58

标签: reactjs i18next react-i18next

我具有以下PHP脚本来加载i18next翻译的资源

<?php
$sql = 'SELECT * FROM translations';
...
header('Content-Type: application/json');
echo json_encode($translations);
?>

但是如何在我的react js应用程序中使用它?最初,我使用i18next官方教程中所做的在客户端加载json的翻译。

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import translations from './translations.json';

const resources = translations;

i18n.use(initReactI18next).init({ resources, lng: 'zh', keySeparator: false, interpolation: { escapeValue: false } });

我想在服务器端使用PHP进行加载。但是以下操作无效:

import i18n from 'i18next';
import xhr from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';
import axios from 'axios';

function loadCurrent(url, options, callback, data) {
    axios.get(url).then((res) => {
       callback(res.data, { status: res.status });
    });
}

const i18nextOpt = {
 backend: {
     loadPath: 'http://localhost/translation.php',
     parse: function(data) { return JSON.parse(data); },
     ajax: loadCurrent
 },  
 getAsync: false
 };

 i18n.use(xhr).init(i18nextOpt);

我的React脚本应该更改什么?谢谢。

1 个答案:

答案 0 :(得分:0)

诀窍是:

通过导入添加资源,您的结构如下:

{ lng: { ns: { key: value } } }

在xhr上每个lng-namespace对都分别加载...因此文件必须是

{ key: value }

但是以lng / ns请求->因此,loadpath类似于:

http://localhost/{{lng}}/{{ns}}.php

https://www.i18next.com/how-to/add-or-load-translations

无需使用axios,只需使用xhr-backend

相关问题