开发者

How to evaluate json member using variable ?

开发者 https://www.devze.com 2022-12-29 02:40 出处:网络
Hi i\'ve got a problem evaluating json. My goal is to insert json member value to a function variable, take a look at this

Hi i've got a problem evaluating json. My goal is to insert json member value to a 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 i load session from php file that i've store beforehand. i store that session variable using 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 $开发者_JS百科_SESSION["$load"];  
}
?>

using firebug, i get expected response but i also received error

> uncaught exception: Syntax error, unrecognized expression: )

pointing at this

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

I wonder how to solve this


The correct code to use is:

id = json[svar];

You may also want to add alert(svar); to check that svar contains the correct value beforehand.

However, your code still won't work: the func_load_session function will return immediately, before the ajax call finishes and before the id variable is assigned.

what you need to do instead is to perform whatever you want to do with id from the ajax callback function:

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


Also If I understand and have full part of your code Your json comes out like Store["var"]="var" ?? Does not appear valid json

I suggest using php function json_encode()

So php would be

 $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"]);  
}
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消