0

While parsing inline JSON object with d3.json(obj, function(error, root), its working properly when I'm running it locally, but when I run on tomcat server I'm getting an XMLHttpparse error. I searched over the Internet. Answer that I found was CORS. But there was no clarity how to achieve this. Could you please help me?

var obj = {
 "name": "vis",
 "children": [
  {
   "name": "Votes",
   "children": [
    {"name": "200", "size": 200,"url":"1"},
    {"name": "500", "size": 500,"url":"2"},
    {"name": "300", "size": 300,"url":"3"},
    {"name": "400", "size": 400,"url":"4"}
   ]
  },  
  {
   "name": "Reputation", 
   "children": [
    {"name": "200", "size": 200},
    {"name": "500", "size": 500},
    {"name": "300", "size": 300},
    {"name": "400", "size": 400}
   ]
  },
  {
   "name": "Accepted Answer",
   "children": [    
    {
     "name": "encoder",
     "children": [
      {"name": "Accepted Answer", "size": 500}
     ]
    }
   ]
  }
 ]
};
d3.json(obj, function(error, root) {
    alert('error '+error);
    alert('root: '+root);
  if (error) return console.log(error);
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Tulasi
  • 25
  • 1
  • 6

2 Answers2

2

First, make sure you are passing in a URL as the first argument to d3.json().

Second, you need to configure Tomcat to support CORS. In version 7.0.41+, Tomcat includes a CORS filter. Add the filter to your web.xml file.

Here's the minimum configuration you need:

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

See the documentation for more information and additional configuration options: http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter

And here's a flowchart of request processing for this filter that may help you with setting up any additional parameters:

CORS flowchart

Community
  • 1
  • 1
Kev H
  • 241
  • 2
  • 9
0

You are misunderstanding what d3.json is used for. d3.json makes an actual AJAX request (hence why in the documentation names the chapter as Requests) so it is literally trying to fetch that obj but can't because it doesn't need to. If you really want to use d3.json, you can move that JSON object into its own file and then reference it by doing d3.json(data.json, function(err, root)).

The result d3.json would return is literally the object you have declared. You can simply assign it to the variable name root.

Related question: d3 js - loading json without a http get

Community
  • 1
  • 1
aug
  • 11,138
  • 9
  • 72
  • 93