How to evaluate json member using variable?

Hi, I have a problem with json rating. My goal is to insert json member value into function variable, take a look at this

function func_load_session(svar){

var id = '';

$.getJSON('data/session.php?load='+svar, function(json){

  eval('id = json.'+svar);

});

return id;

}

this code loads the session from the php file that I stored in advance. I save this session variable with dynamic var.

<?php
/*
* format ?var=[nama_var]&val=[nilai_nama_var]
*/ 

$var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];

session_start();

if($var){
  $_SESSION["$var"] = $val;
  echo "Store SESSION[\"$var\"] = '".$_SESSION["$var"]."'";
}else if($load){
  echo $_SESSION["$load"];  
}
?>

using firebug, I get the expected response, but I also got an error

> uncaught exception: Syntax error, unrecognized expression: )

pointing to this

> eval('id = json.'+svar);

I wonder how to solve this problem?

+3
source share
2 answers

The correct code to use is:

id = json[svar];

You can also add alert(svar);to check that it svarcontains the correct value in advance.

: func_load_session ajax id.

, , , id ajax:

function func_load_session(svar){
    $.getJSON('data/session.php?load='+svar, function(json){
        var id = json[svar];
        doSomethingWith(id);
    });
}
+3

, , json Store [ "var" ] = "var"?? json

php json_encode()

, php

 $var = $_GET['var'];
$val = $_GET['val'];
$load = $_GET['load'];

session_start();

if($var){
  $_SESSION["$var"] = $val;
  echo json_encode(array($var=>$_SESSION[$var])); // or something like that 
}else if($load){
  echo json_encode(array('load'=>$_SESSION["$load"]);  
}
?>
+1

Source: https://habr.com/ru/post/1743324/


All Articles