简体   繁体   中英

create jquery array from php ajax response JSON object

I have an en.php file with an array inside, like this:

$lang = array(
    // MENÚ LATERAL
    "bienvenido" => "Welcome",
    "panel_administracion" => "Administration panel",
    "administracion" => "Administration",
    "gestion_usuarios" => "Users Management",
    "roles_permisos" => "Roles and Permissions",
    "perfiles" => "Profiles",
    "apariencia" => "Appearance",
    "configuracion" => "Settings",
    "gestion_scripts" => "Script Management",
    "gestion_escenarios" => "Scenario Management",
    "planificador" => "Planner",
    "monitorizacion" => "Monitoring",
    "resultados_ejecuciones" => "Executions Results",
    "dashboard" => "Dashboard",
    // USUARIOS
    "usuario" => "User",
    "nombre_pagina" => "Users",
    "nuevo_usuario" => "New User",
    "nombre_usuario" => "User Name",
    "perfil" => "Profile",
    "rol" => "Role",
    "idioma_sitio" => "Language",
    "password" => "Password",
    "repetir_password" => "Repeat Password",
    "guardar" => "Save",
    "administracion_usuarios" => "User administration",
    "actualizar_usuario" => "Edit user",
    "acciones" => "Actions"
);

And I would like store this array in a js array, inside an .js file to access to data always I need, and this code do it this. But I receive this alert: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental ...

var traducciones = function () {
    var tmp = null;
    var action = "getTraducciones";
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': '../egea/lib/egeaAjax/fAjaxUsuarios.php',
        'data': { 'action': action },
        'success': function (data) {
            var datos = JSON.parse(data);
            tmp = datos;
        }
    });
    return tmp;
}();

PHP function:

function getTraducciones(){
    session_start();
    $traducciones = '';
    $u = $_SESSION['usuario'];
    if (isset($u) === true){
        $lang = getLanguage($u);
        if(isset($lang) === true){
            require "../../lang/".$lang.".php";
        }else{
            require "../../lang/es.php";
        }
    }
    echo json_encode($lang);
}

NOTE: async: false is deprecated. How can I do it, without ajax async:false call?. Thanks.

Return promise instead of the value itself:

var traducciones = function () {
    return new Promise((resolve, reject) => {
        var action = "getTraducciones";
        $.ajax({
            'async': true,
            'type': "POST",
            'global': false,
            'dataType': 'html',
            'url': '../egea/lib/egeaAjax/fAjaxUsuarios.php',
            'data': { 'action': action },
            'success': function (data) {
                var datos = JSON.parse(data);
                resolve(datos);
            },
            'error': reject
        });
    });
}();

Then use it like:

traducciones.then(function(datos) {
    // the code that uses the data
}, function() {
    // code called if data loading failed
});

By the way, if you really need to have the data loaded in a synchronous way, you may consider loading it as a JS code instead of JSON – ie replace:

echo json_encode($lang);

in your PHP code with:

Header('Content-type: text/javascript; charset=utf-8');
    // or whatever other charset you are using ^^^^^
echo "var traducciones = " . json_encode($lang) . ";\n";

And then load it as a normal script:

<script src="../egea/lib/egeaAjax/fAjaxUsuarios.php"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM