简体   繁体   English

在没有JSON.parse()的情况下将JSON直接传递给Javascript

[英]Passing JSON directly to Javascript without JSON.parse()

I noticed that many people are passing objects from PHP to Javascript as JSON like this: 我注意到很多人将对象从PHP传递到Javascript,就像这样:

var obj=JSON.parse('<?php echo json_encode($obj) ?>');

or 要么

var obj=jQuery.parseJSON('<?php echo json_encode($obj) ?>');

Why don't people pass JSON directly like this? 为什么人们不直接传递JSON?

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

This works fine with the few objects that I tried. 这适用于我尝试过的少数对象。 Are there cases when this won't work? 有没有这种情况不起作用的情况?

passing objects from PHP to Javascript as JSON like this: 将对象从PHP传递到Javascript,如下所示:

 var obj=JSON.parse('<?php echo json_encode($obj) ?>'); 

Ouch! 哎哟! You're right, this is overcomplicated. 你是对的,这太复杂了。 Also, it actually has serious problems with apostrophes and backslashes in the JSON string, which are not escaped and destroy the string literal. 此外,它实际上在JSON字符串中有撇号和反斜杠的严重问题,它们不会被转义并破坏字符串文字。

Why don't people pass JSON directly? 为什么人们不直接传递JSON?

People who do it properly do it this way indeed. 这样做的人确实这样做。

Are there cases when this won't work? 有没有这种情况不起作用的情况?

Yes. 是。 There are unicode characters that are valid in pure JSON, but a syntax error in JavaScript - see http://timelessrepo.com/json-isnt-a-javascript-subset for details. 有一些unicode字符在纯JSON中有效,但在JavaScript中有语法错误 - 有关详细信息,请参阅http://timelessrepo.com/json-isnt-a-javascript-subset However, json_encode would output these as escape sequences anyway. 但是, json_encode无论如何都会输出这些作为转义序列。

Generally, you'd use JSON parsers to secure situations where the code returned may be erroneous (instead of crashing your script, it will simply throw an exception and keep going). 通常,您使用JSON解析器来保护返回的代码可能是错误的情况(而不是崩溃您的脚本,它只会抛出异常并继续)。 This is generally a good idea when the JSON is sent from a source you don't have control over. 当从您无法控制的源发送JSON时,这通常是个好主意。 It seems unnecessary when you're in control of both ends (PHP server and JS client). 当你控制两端(PHP服务器和JS客户端)时似乎没必要。

That said, a "safer" method just for server side would be: 也就是说,仅服务器端的“更安全”方法是:

<?php $json_encoded = json_encode ($obj); ?>
var obj=<?php echo ($json_encoded ? $json_encoded : 'null'); ?>;

This makes sure only a valid object is passed into JavaScript. 这样可以确保只将有效对象传递给JavaScript。

More info: https://api.jquery.com/jQuery.parseJSON/ 更多信息: https//api.jquery.com/jQuery.parseJSON/

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

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