简体   繁体   中英

How do I use JSON data in D3 which was received from WEB-Service?

So far my program used a .json-file to plot a diagram. Code was something like this:

d3.json("data.json", function(data) {

    //use data

});

This worked perfectly fine. The data in .json-file comes from my own REST-service which is running in NetBeans. For the moment I just copied and pasted the output of my REST-service-call into the .json file (located in the folder where also the index.html is) and saved it. As this is just a dumb way to do it, I want my JavaScript to call my REST-service and use the retrieved data instead of the .json-file. So I tried something like this:

d3.json('http://localhost:port/data', function(data) {

    //use data

});

(the url is obviously just a dummy) Checking the NetBeans-networkmonitor , it's always a GET request with status 200 which should be fine, I guess. The response headers contain "content-type: application/json" and the response itself is the exact same data I'd receive if I just call the url in my browser (from which I copy-pasted them into the .json-file before -> no difference in data). Problem is: the diagram is just not shown anymore. If I run the hmtl with the "file"-code it works, if I run it with the "call Rest-service"-code, it doesn't show anything anymore. Has anybody an idea why this is happening?

Interesting thing is that the response code from my rest-service is red and there's no content-type in the NetBeans network-monitor ( screenshot ).

Edit1: the table from the screenshot does not show a content-type although the response headers say "Content-type: application/json".

I found the solution of the problem thanks to ranjeet8082!

I took a look at the error log of my browser (chrome) by pressing f12 on the index.html. The console displayed the following error:

"XMLHttpRequest cannot load http:// rest-url /data. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'rest-url' is therefore not allowed access."

("rest-url" is the dummy for my rest-url)

I could fix the problem by simply adding the "Allow-Control-Allow-Origin: *"-addon to my chrome-addons. This can be found in this link . Thank you guys for contributing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM