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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7229027/
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-24 01:24:05  来源:igfitidea点击:

how to get data to javascript from php using json_encode?

phpjavascriptcsvjson

提问by Sammy S.

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

然后简单地将成员作为 data[1].latitude 访问

回答by Sammy S.

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>

回答by HoofHarted

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']);

回答by fred

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 页面添加初始值的快速技巧。

回答by Sebastian Viereck

no need for jquery, just:

不需要jquery,只需:

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

回答by Elangovan

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']);

回答by Ahmet K AKARGUL

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}"

回答by Tayyab Hayat

HTML

HTML

<select name="sub" id="subcat" class="form-control" required="required">

</select>

PHP

PHP

$this->load->model('MainModel');
$subvalue = $this->MainModel->loadSubData($var);
echo json_encode($subvalue);
//if MVC
// or you can just output your SQLi data to json_encode()

JS

JS

$("#maincat").change(function(){
  var status = this.value;

  $.ajax({
    type: 'POST',
    url: 'home/subcat/'+status,
    success: function(data){
        var option = '';
        var obj = JSON.parse(data);
        if(obj.length > 0){
            for (var i=0;i<obj.length;i++){
            option += '<option value="'+ obj[i].id + '">' + obj[i].name + '</option>';  
            }
            //Now populate the second dropdown i.e "Sub Category"
            $('#subcat').children("option").remove();
            $('#subcat').append(option);
        }else{
            option = '<option value="">No Sub Category Found</option>';
            $('#subcat').children("option").remove();
            $('#subcat').append(option);
        }       
    },
    error: function(){
    alert('failure');
    }
});