简体   繁体   English

为什么eval()无法与JSON.parse()的输出一起使用?

[英]why eval() doesn't work with output of JSON.parse()?

I want to showcase some javascripts. 我想展示一些JavaScript。 To do so I read the contents of .js files with php file_get_contents() then json_encode() and echo the results, then on the fore end I read the result through $.get() and then I do a JSON.parse() on the results(I have tried not parsing it) but still eval() doesnt work on the result. 为此,我先用php file_get_contents()然后json_encode()读取.js文件的内容并回显结果,然后在前端通过$ .get()读取结果,然后执行JSON.parse()在结果上(我尝试不解析它),但是eval()在结果上不起作用。

Oddly enough if I copy the result of json_encode() and paste it in a js variable then eval() works! 奇怪的是,如果我复制json_encode()的结果并将其粘贴到js变量中,那么eval()会起作用!

What did I do wrong? 我做错了什么?

Server side: 服务器端:

$name=$_GET['name'];
$t=  file_get_contents('../graphics/'.$name);
$t=  json_encode($t);
echo $t;

client side: 客户端:

$.get("php_lib/readGraph.php",{ name:name}, function(data, status){
                    if(status){
                       eval(JSON.parse(data));
                       }
                    else {
                        alert('Ajax error');
                    }
                    });

There's no need to encode your code to json. 无需将您的代码编码为json。 You're not passing on formatted data like variables, you're outputting full javascript code. 您没有传递变量之类的格式化数据,而是输出了完整的javascript代码。 I'd try simply removing the json parts. 我会尝试简单地删除json部分。

Hopefully the PHP you pasted was just a sample, and you are doing serious verification before allowing people to output files from your server. 希望您粘贴的PHP只是一个示例,并且在允许人们从您的服务器输出文件之前,您正在认真进行验证。 Having a path specified in your code is nowhere near enough, since that can easily be circumvented by simply adding .. to the input. 在代码中指定的路径远远不够,因为只需在输入中添加..就可以轻松绕开该路径。 A hacker could then output absolutely everything the user your webserver is running as has read access to. 然后,黑客可以绝对输出您的Web服务器所运行的用户具有读取权限的所有内容。 Even outside your web root. 即使在您的网络根目录之外。 That out of the way, a more efficient way to output a file would be to use readfile() . 顺便说一句,输出文件的更有效方法是使用readfile()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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