0

Javascript has this fin line of code that alerts you what type of object you are working with. It is the following:

alert(Object.prototype.toString.apply(obj))

So, I am working with php and js - extjs 4.2, and looking for a way to pass an associative array created by php to java by using json_encode(). So I did the following:

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

Ext.Ajax.request(
{
    url: 'php/parse.php?id='+buttonText,
    method: 'GET',
    success: function(response) 
    {
        //var obj = response;
        var obj = response.responseText;
        alert(Object.prototype.toString.apply(obj));                    
    },
    failure: function(response) 
    {
        alert('server-side failure with status code ' + response.status);
    }
});

The php part of the code is in parse.php file as you can see from js code. When I alert the obj, it shows a string of json encoded php array. And js says that obj is a string object. If I keep the commented line without responseText, js alerts that obj is an Object but does not say what type (guessing json type).

What i am trying to achieve, is to have a legit js array that will get that php array from response (response is the param. in the function). Thanks

EDIT : my php array structure

array
(
    'vars' => array( 
                   [0] => 'name' => '1', 'value' => 2
                   [1] => ... )
    'file' => array(
                   [0] => 'name' => 'aaa.aa'
                   [1] => ...)
)
Gago
  • 35
  • 2
  • 12

1 Answers1

2

You're asking how to parse a string of JSON-encoded data into Javascript objects.

The built-in JSON.parse function does exactly that.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • So if I do "var arr = JSON.parse(obj)", I will get an js array? – Gago May 23 '13 at 17:43
  • Remember that JavaScript differentiates between a numerically indexed array (Array) and and associative array (Object). If you want the former, your JSON should look like `["item1","item2"]`. If you want an associative array, the JSON can look like: `{"key1":"item1","key2":"item2"}`. To answer your question, you may get an Array or Object depending on the syntax of `obj`. – J.D. Pace May 23 '13 at 17:48
  • I am going to edit the array struct that will be echoed by php above, can you answer to it based on the struct...thanks alot – Gago May 23 '13 at 17:50
  • @Brian: `JSON.parse` will return Javascript arrays or objects based on whatever the JSON _is_. Use your debugger (or `console.log`) to see what it returns. – SLaks May 23 '13 at 17:57