将PHP JSON传递给Javascript:echo json_encode vs echo json声明 [英] Passing PHP JSON to Javascript: echo json_encode vs echo json declaration

查看:64
本文介绍了将PHP JSON传递给Javascript:echo json_encode vs echo json声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个常见的常量文件,在php和javascript之间共享,使用JSON存储常量。但我想知道为什么使用 json_encode()将JSON从PHP传递给javascript而不是回显json声明。

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 JSON

Let's say I have the PHP JSON

<?php 

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

?>

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

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

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

然后我相信我必须使用类似 $。getScript()的东西读取php文件以获取 $ json_obj 然后使用 parseJSON()来制作它可用于javascript。

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

但为什么不呢?

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

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

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

是否有一个特殊原因,为什么使用 json_encode()更为有利,然后简单地回应声明JavaScript的?

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

推荐答案

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

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

这篇关于将PHP JSON传递给Javascript:echo json_encode vs echo json声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆