如何使用json_encode从php获取数据到javascript?

时间:2022-12-21 21:34:04

I am trying to map traceroutes to google maps.

我正在尝试将traceroutes映射到谷歌地图。

I have an array in php with traceroute data as

我在php中有一个带有traceroute数据的数组

$c=ip,latitude,longitude, 2nd ip, its latitude, longitude, ....target ip, its lat, its lng

I used json_encode($c, JSON_FORCE_OBJECT) and saved the file

我使用了json_encode($ c,JSON_FORCE_OBJECT)并保存了文件

Now, how do I access this using javascript, by directly equating it to new JS object?

现在,我如何使用javascript访问它,直接将它等同于新的JS对象?

earlier I used to have a data format like this on harddrive

早些时候我以前在硬盘上有这样的数据格式

var data12 = {

"route":[
{
    "ip": "some ip",

    "longitude": "some lng",

    "latitude": "some lat",

.....

and in my javascript it was used as

在我的javascript中它被用作

data=data12.route;

and then simply acces the members as data[1].latitude

然后简单地将成员作为数据[1] .latitude进行访问

7 个解决方案

#1


25  

I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.

我建议使用jQuery库。缩小版本的大小仅为31 kB,并提供许多有用的功能。

For parsing JSON, simply do

要解析JSON,只需执行

var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );

You can now access everything easily:

您现在可以轻松访问所有内容:

alert ( obj.name );

Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.

注意:jQuery使用浏览器的本机JSON解析器 - 如果可用 - 这比使用eval()方法更快,更安全。

Edit: To get data from the server side to the client side, there are two possibilities:

编辑:要从服务器端向客户端获取数据,有两种可能:

1.) Use an AJAX request (quite simple with jQuery):

1.)使用AJAX请求(使用jQuery非常简单):

   $.ajax ( {
       url: "yourscript.php",
       dataType: "json",
       success: function ( data, textStatus, jqXHR ) {
           // process the data, you only need the "data" argument
           // jQuery will automatically parse the JSON for you!
       }
   } );

2.) Write the JSON object into the Javascript source code at page generation:

2.)在页面生成时将JSON对象写入Javascript源代码:

   <?php
       $json = json_encode ( $your_array, JSON_FORCE_OBJECT );
   ?>

   <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

   <script type="text/javascript">
   //<![CDATA[

   var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );

   //]]>
   </script>

#2


1  

I could get the JSON array by using PHP's json_encode() from backend like this example:

我可以通过使用来自后端的PHP的json_encode()来获取JSON数组,如下例所示:

<!doctype html>
<html>
    <script type="text/javascript">
        var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
        console.log(json[1]);
        console.log(json.abc);
    </script>        
</html>

No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.

没有引号表示打印出的任何内容的eval()。这是我们经常用来快速添加初始值到AJAX页面的快速入侵。

#3


1  

I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.

我知道这是旧的,但我最近发现自己在寻找这个。这里的答案都没有适用于我的案例,因为我的价值观中有引号。这里的想法是在回显到页面之前对数组进行base64编码。这样引号不会发生冲突。

< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);

#4


0  

no need for jquery, just:

不需要jquery,只需:

    var array= <?php echo json_encode($array); ?>;
    console.log(array->foo);

#5


0  

we have to display the json encode format in javascript , by using below one:

我们必须在javascript中显示json编码格式,使用下面的一个:

var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);

#6


0  

This function works for you I guess:

我猜这个功能对你有用:

    function json_encode4js($data) {
    $result = '{';
    $separator = '';
    $count = 0;
    foreach ($data as $key => $val) {

        $result .= $separator . $key . ':';
        if (is_array($val)){
            $result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
            continue;
        }
        if (is_int($val)) {
            $result .= $val;
        } elseif (is_string($val)) {
            $result .= '"' . str_replace('"', '\"', $val) . '"';
        } elseif (is_bool($val)) {
            $result .= $val ? 'true' : 'false';
        } elseif (is_null($val)) {
            $result .= 'null';
        } else {
            $result .= $val;
        }

        $separator = ', ';
        $count++;
    }

    $result .= '}';

    return $result;
}

$a = array(
"string"=>'text',
'jsobj'=>[
    "string"=>'text',
    'jsobj'=>'text2',
    "bool"=>false
    ],
"bool"=>false);

var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}" 

var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"

#7


-2  

Simply eval() the data in Javascript.

只需在Javascript中eval()数据。

#1


25  

I recommend using the jQuery library. The minified version only has 31 kB in size and provides lots of useful functions.

我建议使用jQuery库。缩小版本的大小仅为31 kB,并提供许多有用的功能。

For parsing JSON, simply do

要解析JSON,只需执行

var obj = jQuery.parseJSON ( ' {"name" : "John"} ' );

You can now access everything easily:

您现在可以轻松访问所有内容:

alert ( obj.name );

Note: jQuery uses the browser's native JSON parser - if available - which is very quick and much safer then using the eval () method.

注意:jQuery使用浏览器的本机JSON解析器 - 如果可用 - 这比使用eval()方法更快,更安全。

Edit: To get data from the server side to the client side, there are two possibilities:

编辑:要从服务器端向客户端获取数据,有两种可能:

1.) Use an AJAX request (quite simple with jQuery):

1.)使用AJAX请求(使用jQuery非常简单):

   $.ajax ( {
       url: "yourscript.php",
       dataType: "json",
       success: function ( data, textStatus, jqXHR ) {
           // process the data, you only need the "data" argument
           // jQuery will automatically parse the JSON for you!
       }
   } );

2.) Write the JSON object into the Javascript source code at page generation:

2.)在页面生成时将JSON对象写入Javascript源代码:

   <?php
       $json = json_encode ( $your_array, JSON_FORCE_OBJECT );
   ?>

   <script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>

   <script type="text/javascript">
   //<![CDATA[

   var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );

   //]]>
   </script>

#2


1  

I could get the JSON array by using PHP's json_encode() from backend like this example:

我可以通过使用来自后端的PHP的json_encode()来获取JSON数组,如下例所示:

<!doctype html>
<html>
    <script type="text/javascript">
        var json = <?php echo json_encode(array(1 => '123', 'abc' => 'abd', 2 => 5));?>;
        console.log(json[1]);
        console.log(json.abc);
    </script>        
</html>

No quotation marks means an eval() of whatever was printed out. This is a quick hack that we utilised often to quickly add initial values to our AJAX page.

没有引号表示打印出的任何内容的eval()。这是我们经常用来快速添加初始值到AJAX页面的快速入侵。

#3


1  

I know this is old, but I recently found myself searching for this. None of the answers here worked for my case, because my values had quotes in them. The idea here is to base64 encode the array before echo'ing to the page. That way the quotes don't conflict.

我知道这是旧的,但我最近发现自己在寻找这个。这里的答案都没有适用于我的案例,因为我的价值观中有引号。这里的想法是在回显到页面之前对数组进行base64编码。这样引号不会发生冲突。

< ?php
$names = ['first' => "some'name"];
?>
var names = JSON.parse(atob('< ?php echo base64_encode(json_encode($names)); ?>'));
console.log(names['first']);

#4


0  

no need for jquery, just:

不需要jquery,只需:

    var array= <?php echo json_encode($array); ?>;
    console.log(array->foo);

#5


0  

we have to display the json encode format in javascript , by using below one:

我们必须在javascript中显示json编码格式,使用下面的一个:

var responseNew = JSON.parse(' {"name" : "John"} ' );
alert(responseNew['name']);

#6


0  

This function works for you I guess:

我猜这个功能对你有用:

    function json_encode4js($data) {
    $result = '{';
    $separator = '';
    $count = 0;
    foreach ($data as $key => $val) {

        $result .= $separator . $key . ':';
        if (is_array($val)){
            $result .= json_encode4js($val).(!$separator && count($data) != $count ? ",":"");
            continue;
        }
        if (is_int($val)) {
            $result .= $val;
        } elseif (is_string($val)) {
            $result .= '"' . str_replace('"', '\"', $val) . '"';
        } elseif (is_bool($val)) {
            $result .= $val ? 'true' : 'false';
        } elseif (is_null($val)) {
            $result .= 'null';
        } else {
            $result .= $val;
        }

        $separator = ', ';
        $count++;
    }

    $result .= '}';

    return $result;
}

$a = array(
"string"=>'text',
'jsobj'=>[
    "string"=>'text',
    'jsobj'=>'text2',
    "bool"=>false
    ],
"bool"=>false);

var_dump( json_encode4js($a) ); //output: string(77) "{string:"text", jsobj:{string:"text", jsobj:"text2", bool:false}, bool:false}" 

var_dump( json_encode($a));//output: string(85) "{"string":"text","jsobj":{"string":"text","jsobj":"text2","bool":false},"bool":false}"

#7


-2  

Simply eval() the data in Javascript.

只需在Javascript中eval()数据。