将 PHP JSON 传递给 Javascript:echo json_encode 与 echo json 声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18528692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:44:13  来源:igfitidea点击:

Passing PHP JSON to Javascript: echo json_encode vs echo json declaration

phpjavascriptjqueryjson

提问by roverred

I'm trying to create a common constants file to share between php and javascript, using JSON to store the constants. But I'm wondering why pass the JSON from PHP to javascript using json_encode()over echoing the json declaration.

我正在尝试创建一个通用常量文件以在 php 和 javascript 之间共享,使用 JSON 来存储常量。但我想知道为什么使用json_encode()过度响应 json 声明将 JSON 从 PHP 传递到 javascript 。

Let's say I have the PHP JSON

假设我有 PHP JSON

<?php 

$json_obj = '{"const1": "val",
            "const2": "val2"             
                            }';

?>

Googling, it seems the typical way of passing back to javascript is using

谷歌搜索,似乎传递回 javascript 的典型方法是使用

<?php echo json_encode($json_obj); ?>

Then I believe I would have to use something like $.getScript()to read the php file to get $json_objand then use parseJSON()to make it useable in javascript.

然后我相信我将不得不使用类似$.getScript()读取 php 文件的方法来获取$json_obj,然后使用parseJSON()它来使其在 javascript 中可用。

But why not instead

但为什么不呢

<?php  echo 'var json = '.$json_obj; ?>

This way all you have to do is load the script directly and you have the json ready to use directly.

这样你所要做的就是直接加载脚本,你就可以直接使用 json 了。

Is there a particular reason why it is more favorable to use json_encode()then simply echoing the declaration to javascript?

有什么特别的原因为什么使用比json_encode()简单地将声明回显到 javascript更有利?

采纳答案by Tobias Golbs

In your case $json_objis already a string. So it is not necessary. But if you have an array you want to pass to javascript json_encodewill help you with this.

在你的情况下$json_obj已经是一个字符串。所以没有必要。但是,如果您有一个要传递给 javascript 的数组,json_encode它将帮助您解决这个问题。

回答by kamituel

It all depends on what you want to send from server to the client - be it a data (JSON) or some code.

这一切都取决于您想要从服务器发送到客户端的内容 - 无论是数据 (JSON) 还是一些代码。

Two approaches:

两种做法:

  1. Echo a JSON file on a server - then you print your JSON document and set response Content-Typeto application/json. This way you can use any AJAX library you wish, like $.getor raw XMLHttpRequestetc. It is a way of passing data.

  2. Echo a Javascript code on a server and then use $.getScriptto load it. It's a way of passing code. This is potentially less secure, because your code can contain not only JSON, but also any arbitary code. So if attacker can compromise your server, he could be able to push code to any client for a remote execution.

  1. 在服务器上回显 JSON 文件 - 然后打印 JSON 文档并将响应设置Content-Typeapplication/json. 这样你就可以使用任何你想要的 AJAX 库,像$.get或原始XMLHttpRequest等。这是一种传递数据的方式。

  2. 在服务器上回显 Javascript 代码,然后使用$.getScript它来加载它。这是一种传递代码的方式。这可能不太安全,因为您的代码不仅可以包含 JSON,还可以包含任何任意代码。因此,如果攻击者可以破坏您的服务器,他就可以将代码推送到任何客户端以进行远程执行。

If you want to pass data only, go with first approach. It's cleaner and more safe.

如果您只想传递数据,请使用第一种方法。它更清洁、更安全。

Additionally, if you ever end up writing frontend in different environment, say different programming language, you'll be able to resuse the same JSON-returning endpoint. It'll be harder if you return Javascript code.

此外,如果您最终在不同的环境中编写前端,比如不同的编程语言,您将能够重用相同的 JSON 返回端点。如果返回 Javascript 代码会更难。

回答by Kashinath Patil

Passing PHP JSON to Javascript and reading
var stuff = <?php print json_encode($datajson); ?>; var arr = new Array(); arr= JSON.parse(stuff); document.write((arr[0].cust_code );

将 PHP JSON 传递给 Javascript 并读取
var stuff = <?php print json_encode($datajson); ?>; var arr = new Array(); arr= JSON.parse(stuff); document.write((arr[0].cust_code );

回答by 3k-

Usually this is what I do, the safest way I've found:

通常这就是我所做的,我发现的最安全的方法:

// holds variables from PHP
var stuff = {};
try {
    // stuff will always be an object
    stuff = JSON.parse('<?php echo empty($stuff) ? '{}' : json_encode($stuff) ?>');
} catch (e) {
    if (e instanceof SyntaxError)
    {
        // report syntax error
        console.error("Cannot parse JSON", e);
    }
}
// show resulting object in console
console.log("stuff:", stuff);

回答by Luc

Even though it may seem like overkill for your particular problem, I would go for the json_encode/parse option still. Why? you ask. Well, think of it as avoiding duplication. If you encode/parse you can keep the constants in an object easily readable by you PHP-code. And the same for your JS code.

尽管对于您的特定问题似乎有些矫枉过正,但我​​仍然会选择 json_encode/parse 选项。为什么?你问。好吧,将其视为避免重复。如果您编码/解析,您可以将常量保存在 PHP 代码易于阅读的对象中。您的 JS 代码也是如此。

It simply eliminates the need to fiddle with it.

它只是消除了摆弄它的需要。

回答by RONE

constant.php

常量.php

<?php
$array = array("const1" => "val", "const2" => "val2");
?>
<script>
var contants = <?php echo json_encode($array); ?>
</script>

======================END OF FILE constant.php=======

======================END OF FILE constant.php========

In php you can access using

在 php 中,您可以使用

$array["<key>"]

In javascript, you can access using

在javascript中,您可以访问使用

contants.const1, ....

回答by SixteenStudio

json_encodeis a function that converts a PHP array into a JSON string, and nothing more. Since your $json_objvariable is alreadya JSON string, no further conversion is needed and you can simply echo it out.

json_encode是一个将 PHP 数组转换为 JSON 字符串的函数,仅此而已。由于您的$json_obj变量已经是 JSON 字符串,因此无需进一步转换,您只需将其回显即可。

To get to your $json_objstring from an array your code would have looked like this

要从$json_obj数组中获取字符串,您的代码将如下所示

$json_array = array(
    "const1" => "val",
    "const2" => "val2"
);

$json_obj = json_encode($json_array);

回答by jcubic

You use json_encodeif you use php array not a string:

您可以使用json_encode,如果你使用PHP数组不是字符串:

$array = array("const1" => "val", "const2" => "val2");

echo json_encode($array);

if you call json_encode on a string you will get:

如果你在一个字符串上调用 json_encode 你会得到:

"{\"const1\": \"val\", \"const2\": \"val2\"}"

回答by Barmar

The argument to json_encode()should be a PHP data structure, not a string that's already in JSON format. You use this when you want to pass a PHP object to Javascript.

的参数json_encode()应该是一个 PHP 数据结构,而不是一个已经是 JSON 格式的字符串。当您想将 PHP 对象传递给 Javascript 时,您可以使用它。