简体   繁体   中英

Can't get JSON data from file from local domain URL (Django static file)

I want to load data from a JSON file to use with d3.js

I'm using Django and the URL of the the JSON file json_path looks like this: /staticfile/example.json . I'm using the following code to read the data and do things:

d3.json(json_path, function(error, data){
    // Do stuff with data
}

Everything works fine if I use the local IP of the server on the browser: 192.168.xx .

However, when I use the local domain foo.com that points to 192.168.xx , I can't load the data anymore from d3.json() . data is null and I can't understand the content of error .

I'm missing something obvious probably related to callbacks or something but I have trouble understanding the big picture. The whole Django server works perfectly well from both 192.168.xx and foo.com and everything is local. Any ideas?

error is:

XMLHttpRequest​mozAnon: false
mozSystem: false
​onabort: null
​onerror: function respond()​
onload: function respond()​
onloadend: null
​onloadstart: null
onprogress: function onprogress()​
onreadystatechange: null​
ontimeout: null​
readyState: 4
​response: ""​
responseText: ""
​responseType: ""​
responseURL: ""
​responseXML: null
​status: 0
statusText: ""
​timeout: 0​
upload: XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, … }​
withCredentials: false​
<prototype>: XMLHttpRequestPrototype { open: open(), setRequestHeader: setRequestHeader(), send: send(), … } page:472:7

I'm using a library that uses D3 version 3.5.2 and can't update in this particular case.

In general, D3 has not prioritized really robust AJAX support the way that jQuery and other libraries have, because that's not its focus - so if you want to load a wide variety of external resources, like json data, you should probably do so with a 3rd-party library that has more support for carefully tweaked AJAX calls.

Or simply using XMLHttpRequest wrapped in a makeRequest function:

function makeRequest(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", json_path, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onreadyStatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            callback(JSON.parse(xhr.response));
        }
    };
    xhr.onerror = function(error) {
        throw error;
    }
    xhr.send(); 
};

makeRequest(json_path, function(json_response) {
    //here you can use D3 to load your json as you want
    console.log(json_response);
});

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