如何将 json 编码的 PHP 数组转换为 Javascript 中的数组?

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

How to convert json encoded PHP array to an array in Javascript?

phpjavascriptajaxarraysjson

提问by OM The Eternity

I am fetching a JSON encoded array using AJAX from a PHP file, but in JavaScript I need to use it as an array, how can I create an array in Javascript?

我正在使用 AJAX 从 PHP 文件中获取 JSON 编码的数组,但在 JavaScript 中我需要将它用作数组,如何在 Javascript 中创建数组?

My AJAX call to PHP File:

我对 PHP 文件的 AJAX 调用:

  $.ajax({
    type:"POST",
    url:"ajaxfetch.php",
    success:function(result){
            alert(result);
             }
    });

ARRAY Created in PHP File :

在 PHP 文件中创建的数组:

Array
(
    [0] => Array
        (
            [id] => 4
            [deviceID] => xyz123
            [latitude] =>  -33.80010128657071
            [longitude] => 151.28747820854187
            [altitude] => 34.78788787
            [createdDate] => 2013-08-15 23:00:00
            [delete] => 0
        )

    [1] => Array
        (
            [id] => 5
            [deviceID] => jdkfhjskh344
            [latitude] => -33.950198
            [longitude] => 151.259302
            [altitude] => 76.44455
            [createdDate] => 2013-08-15 21:50:42
            [delete] => 0
        )

    [2] => Array
        (
            [id] => 1
            [deviceID] => abc223
            [latitude] => -33.890542
            [longitude] => 151.274856
            [altitude] => 21.4454455
            [createdDate] => 2013-08-15 20:00:00
            [delete] => 0
        )

)

I json encoded this array in PHPbut AJAX retrieved it and is outputted in a string.

我 json 用 PHP 编码了这个数组,但 AJAX 检索了它并以字符串输出。

ABOVE ARRAY json encode as given below:

ABOVE ARRAY json 编码如下:

$data = array();
$data = $locate_obj->getAllDeviceLocation();


echo json_encode($data);

Output of json_encode

json_encode 的输出

[{"id":"4","deviceID":"xyz123","latitude":" -33.80010128657071","longitude":"151.28747820854187","altitude":"34.78788787","createdDate":"2013-08-15 23:00:00","delete":"0"},{"id":"5","deviceID":"jdkfhjskh344","latitude":"-33.950198","longitude":"151.259302","altitude":"76.44455","createdDate":"2013-08-15 21:50:42","delete":"0"},{"id":"1","deviceID":"abc223","latitude":"-33.890542","longitude":"151.274856","altitude":"21.4454455","createdDate":"2013-08-15 20:00:00","delete":"0"}]

I'm looking for the way I can create an array in Javascript with the output I recieve in ajax response, so that I can come up with an array of format:

我正在寻找可以使用我在 ajax 响应中收到的输出在 Javascript 中创建数组的方法,以便我可以想出一个格式数组:

var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

回答by Felix Kling

There are three solution to this problem:

这个问题有以下三种解决方案:

If you want to modify the structure on the client side, have a look at Access / process (nested) objects, arrays or JSON.

如果您想在客户端修改结构,请查看Access / process (nested) objects, arrays or JSON

回答by Fabor

http://api.jquery.com/jQuery.getJSON/

$.getJSON('ajaxfetch.php', function(data) {
  var locations = []; 

  $.each(data, function(key, val) {
    locations[val.deviceID] = [];
    locations[val.deviceID].push(val.id);
    locations[val.deviceID].push(val.latitude);
    locations[val.deviceID].push(val.longitude);
  });
});

Not 100% tested but it's along the right lines. Unsure where you get the location name from as it's not in the array so I used deviceID. Using getJSON should make your life easier.

不是 100% 测试,但它沿着正确的路线。不确定从哪里获取位置名称,因为它不在数组中,所以我使用了 deviceID。使用 getJSON 应该会让您的生活更轻松。

回答by Madara's Ghost

Make sure your output is valid JSON, then specify the dataType: "json"in your jQuery AJAX request:

确保您的输出是有效的 JSON,然后dataType: "json"在您的 jQuery AJAX 请求中指定:

$.ajax({
    type: "POST",
    url: "ajaxfetch.php",
    dataType: "json",
    success: function (result) {
        console.log(result); //Now a JSON object
    }
});

回答by rebroken

var locations = [];
$.ajax({
    type: "POST",
    url: "ajaxfetch.php",
    dataType: "json",
    success: function (result) {
       result.forEach(function(loc) { locations.push(new Array(loc.deviceID, loc.latitude, loc.longitude, loc.id)) });
       // locations is now in desired format (except non-existent place name)
    }
});