2012-03-10 147 views
0

我使用JSON字符串从PHP在JavaScript中传递变量:从PHP传递变量给JavaScript

while($row = mysql_fetch_array($result)) 
     { 
       $tmp = array('id'=>$row['id'], 'alert_type_id'=>$row['alert_type_id'], 'deviation'=>$row['deviation'], 'threshold_low'=>$row['threshold_low'], 'threshold_high'=>$row['threshold_high']) ; 
       $settings[] = $tmp ; 
     } 

     echo '{"data":'.json_encode($settings).'}' ; 
在Javascript

,我使用下面的代码片段:

console.log(result) ;     
var json = eval('('+ result +')') ; 

和出现在控制台中的是以下错误:

1{"data":[{"id":"1","alert_type_id":"1","deviation":null,"threshold_low":"20","threshold_high":"80"}]} 

SyntaxError: Expected token ')' 

请问您能帮我解决这个问题吗? 非常感谢。

回答

0

那么这行代码是无效的。

写在控制台:

'(1{"data":[{"id":"1","alert_type_id":"1","deviation":null,"threshold_low":"20","threshold_high":"80"}]})' 

因为这是你传递什么样的eval功能。我应该给你同样的错误。

如果你想保存在一个变量字符串,你需要调整它一下:

eval('var x =' + result); 

反正它看起来像你做得不对,请重新检查你为什么需要TI使用“邪恶“eval

+0

是不是像:'('+ result +')'我很抱歉,但我没有得到什么错 – user690182 2012-03-10 20:54:30

+0

@ user690182。不,这不对。它只会在'()'侧面运行字符串“command”。你想用'json'做什么? – gdoron 2012-03-10 20:56:54

+0

谢谢,我写了你刚刚在PHP中所说的:echo'('。'{“data”:'。json_encode($ settings)。'}'。')';现在一切正常:)谢谢 – user690182 2012-03-10 20:58:06

2

在你的PHP,你可能想使用json_encode编码您的所有数据:

$result = array(
    'data' => json_encode($settings) 
); 

echo json_encode($result); 

其次,在你的JavaScript,eval很少(永远)是一个好主意。来自Douglas Crockford的风格指南:

eval函数是JavaScript中滥用最多的功能。躲开它。

相反,你可能想使用JSON.parse()重建服务器返回的结果:

console.log(result) ;     
var resultObj = JSON.parse(result); 
console.log(resultObj); 

如果你的代码仍然是断开的,你可能要仔细检查你的PHP,以确保它不会超出json_encode声明的任何输出。

1

东西在你的json字符串前输出“1”。 Javascript在eval()期间无法正确解析。