tags:

views:

42

answers:

1

My js code simply gets a json object from my server, but I think it should be automatically parsed and turned into an object with properties, yet it's not allowing access properly.

    $.ajax({
      type: 'POST',
      url: '/misc/json-sample.js',
      data: {href: path}, // THIS IS THE POST DATA THAT IS PASSED IN; safe2ignore.
      dataType: 'json',
      success: function (datax) {

  if (datax.debug) {
    alert('Debug data: ' + datax.debug);
  }  else {
         alert('No debug data: ' + datax.toSource()  ) ; 
      }

The /misc/json-sample.js file is: [ { "path": "examplemodule/parent1/child1/grandchild1", "title": "First grandchild option", "debug": "First grandchild option", "children": false } ]

(I have also been trying to return that object from drupal as follows, and the same results.) Drupal version of misc/json-sample.js:

 $items[] = array(
      'path' => 'examplemodule/parent1/child1/grandchild1',
      'title' => t('First grandchild option'),
          'debug' => t('debug me!'),
      'children' => FALSE
    );
    print  drupal_to_js($items);

What happens (in FF, which has the toSource() capability) is the alert with 'No debug data: [{path:"examplemodule/parent1/child1/grandchild1", title:"First grandchild option", debug:"First grandchild option", children:false}]' Thanks

+2  A: 

You need to set the Content-Type header to application/json.

header("Content-Type: application/json");
print  drupal_to_js($items);
Michael
Thanks. I tested the change recommended by Michael in the drupal version. It does seem this directive is now part of the header, as when I load the URL directly from localhost as /ra/js then FF asks me "what should FF do with this application/json" -- BUT the jquery app still does not parse the results properly and the same alert is called.
pete
I think I've got it. [ { "path": "examplemodule/parent1/child1/grandchild1", "title": "First grandchild option", "debug": "First grandchild option", "children": false } ] is an ARRAY of objects! Without the [], the .js dummy-filed was parsed properly. Hence, I'm probably referencing the .debug wrong, as that is not an element of the list but an element of the first item in the list.
pete