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

This question already has an answer here:

  • Parse JSON in JavaScript? [duplicate] 16 answers

  • There are three solution to this problem:

  • Call JSON.parse explicitly and pass the response text to it. The return value will be a JavaScript data type.

  • Set the dataType: 'json' option in your $.ajax call so that jQuery parses the JSON for you.

  • Set the right response headers for JSON in PHP. jQuery will detect the header and parse the JSON automatically as well.

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


    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.


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

    $.ajax({
        type: "POST",
        url: "ajaxfetch.php",
        dataType: "json",
        success: function (result) {
            console.log(result); //Now a JSON object
        }
    });
    
    链接地址: http://www.djcxy.com/p/8484.html

    上一篇: 在Ext JS 4或JavaScript中解析JSON

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