douyuben9434 2014-02-11 20:47
浏览 42
已采纳

无法使JSON解析和eval在JavaScript中工作

As I stated above, I have a PHP script and a JavaScript, I have a few objects that read text files on the server side and then pass the data to the JavaScript.

Here's my entire code:

map.html: http://www.pastebin.com/b45mbvgp and index.php: http://www.pastebin.com/zibdquzu

The part that really matters:

var x = <?php echo json_encode($streetsObject); ?>;
var obj = eval("("x")");

I've also tried

var obj = JSON.parse(x);

the X variable does get set to the size of the passed object, 527 (tested it) but when I try to use the eval or JSON parse function is simply doesn't work. Do I have some sort of mistake in my html code which is messing with my calls to other libraries? If so that would be weird because kinetic.js is working just fine. I've been googling examples of JSON and I have yet to see an example of parsing a passed object, it's all examples of local objects :(

(Code works fine if I remove eval / json line of code)

  • 写回答

1条回答 默认 最新

  • drbouzlxb92333332 2014-02-11 20:49
    关注

    Simply do:

    var obj = <?php echo json_encode($streetsObject); ?>;
    

    JSON means JavaScript Object Notation. If you insert JSON directly to Javascript, it will run fine, just in this case. No parsing needed. eval is not recommended to use for JSON parsing, but the same applies to that (note that eval actually works because JSON is valid Javascript!).

    JSON.parse is only needed if you have JSON in a Javascript string. So this would work:

    var str = '<?php echo json_encode($streetsObject); ?>';
    var obj = JSON.parse(str);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀