Ensuring that I accurately input the path to my JSON file within a JavaScript file

In my project using Python 3.6.4 and Django 2.0, I am facing an issue with loading a JavaScript file script.js in an index.html. The problem lies in correctly specifying the path to a JSON file data.json.

Despite utilizing a XmlHttpRequest object, the index.html is not displaying the information from data.json as intended.

function makeRequest(url){
...
    http_request = new XMLHttpRequest();
    http_request.open('GET', url, true);
}
...
window.onload = function(){
    makeRequest("here/have/problems");
}

Tree of my files
https://i.sstatic.net/0tFcu.png

Within index.html, I am using:

{% load static %}
...
<script src="{% static 'bar/scripts/script.js' %}"></script>

This part works well. However, when trying to specify "bar/data/data.json" inside script.js, it doesn't work as expected. Please guide me on resolving this issue.

Answer №1

To ensure accuracy, always include the full path with the leading slash - like this: "/static/bar/data/data.json".

An effective method to prevent hard-coding the full path is by utilizing the {% static %} tag to establish a universal JS variable within a separate <script> section in your template.

Answer №2

If you want to navigate up a level in the directory, simply use two dots and a forward slash ("../"). In order to escape from the templates/bar/ directory, you will need to go up two levels.

{% static '../../bar/scripts/script.js'%}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filter JSON data in AngularJS ng-repeat by a specific ID

I'm having difficulty getting this to function properly. I've been attempting to filter a JSON file by specific ID and then iterate using ng-repeat. Here's what I have tried: This is the button trigger: <a href="#/compare-details">& ...

Can Realm be integrated with Angular 2 for development?

Exploring the compatibility of Realm Mobile Platform with an Angular 2 app has been quite challenging. It seems that integrating the Javascript version of Realm in Angular 2 is not straightforward. I managed to run npm install --save realm successfully and ...

Submitting a Form with Multiple Pages

I'm encountering a challenge that I'm struggling to work through. Initially, we had a professional build our website, but since parting ways with the company, I've taken over site management. While I can handle basic tasks, I lack the expert ...

The error message "Invalid JSON payload. Root element needs to be a message" is returned when using the Google Sheets API with python 2.7

I have been struggling with an error for several weeks now and have attempted solutions from previously asked questions regarding the Python API for Google Sheets. Every time I make a "write" request to my spreadsheet using the Google Sheets API for Pytho ...

Can anyone explain how to pass a toggle state along with its onChange function in Ionic React?

Imagine I have this toggle element: <IonToggle id="IonToggleDarkMode" slot="end" checked={vars.darkMode} onChange={darkModeToggle}></IonToggle> The value of vars.darkMode represents the current state of the toggle, which is ...

The result obtained from response.download() is saved as a blob that may contain undefined elements

I am in the process of developing a client-server certificate generator. In terms of the Backend, I have set up two endpoints: / This endpoint receives a JSON containing extracted data from inputs, sanitizes them, and determines if they are valid or not ...

Error encountered: DOMException - Prevented a frame originating from "domain_name" from accessing a different origin frame

Utilizing the Mautic newsletter for my website has been a great experience. Here is the js code I've been using: /** This section should only be included once per page if manually copying **/ if (typeof MauticSDKLoaded == 'undefined') { ...

Retrieving JSON data from Firebase and transforming it into an array containing identical values [Swift]

Recently, I've been working with a JSON database in Firebase that looks something like the snippet below: "Trips" : { "-KnH34F_WZYNHMsTzj0X" : { "Distance" : 500, "Transport" : "Walk", "TripName" : "Work" ...

What is the best way to add content to fill the empty space left after a column has been hidden in a column

Is there a way to automatically adjust the space when a column is hidden by clicking on the legend item? <div id="container" style="height: 300px"></div> <script src="http://code.highcharts.com/highcharts.src.js"></script> var ...

There was an error in the code: Unexpected token M

Is there a solution for this error that anyone can share? The Google Developer Tools are not able to identify the exact location of the problematic code, making troubleshooting difficult. I am using Meteor and MongoDB. I have looked into Unexpected toke ...

Advancement in the processing time of a HTTP response that is significantly prolonged

I am seeking a way to return an array of JSON objects (requested by an AJAX call in an AngularJS web application) that represent specific files on the server implemented with node.js. Typically, the result is quickly accessed from a database. However, if ...

Pressing a button to input a decimal in a calculator

I am encountering an issue with inputting decimals in my JavaScript. I have a function that checks if the output is Not a Number (NaN). If it is, I want it to output a decimal instead. I attempted to add another conditional statement like this: var opera ...

jQuery tooltip box not functioning correctly

When the mouse enters on li a, the tooltip box (class .show_tooltip) is appearing on the left. I want each tooltip box to display just above or to the left of the link that the mouse is on. The links need to stay on the right as they are now, so please do ...

Utilizing JSON for autocomplete feature with multiple variables

Seeking guidance on resolving an issue. Currently working on the main page of the project (index.php). The script below is fetching values from fetch.php and displaying them correctly. The challenge I am facing is with autocompleting the input boxes for c ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

Transferring a variable value between functions using autocomplete and AJAX communication

I am facing difficulties with implementing autocomplete jQuery along with AJAX call. The issue arises when a user enters text in the input field, triggering an AJAX POST request to the controller which retrieves values from the database and sends them back ...

Employing conditional statements to adjust the size of an image or background identifier in JavaScript

As I dive into the world of Javascript, I find myself faced with the challenge of modifying existing code using if / else statements. The original code snippet in question is as follows: document.getElementById("button1").addEventListener("click", functio ...

Determine the total value of a specific key within a collection of objects

I am grappling with an array of objects: let fileArray = [ { filename: 'File1.txt', bytes: 12345, created: 1548360783511.728 }, { filename: 'File2.txt', bytes: 34567, created: 1548361491237.182 }, { filename: 'File3.txt&apos ...

Remove multiselect label in PrimeNG

I am attempting to change the multiselect label of selected items and replace it with a static default label. Here is what it currently shows: https://i.sstatic.net/qBNHG.png This is what I have tried: .p-multiselect-label { visibility: collapse; ...

What are some ways we can enhance Map.get for react-router using ES6 Maps?

I recently implemented a map using new Map() to store my RR4 configuration within my application. My goal is to retrieve the values associated with /countries/:id when accessing /countries/1. routesMap.get('/countries/1') // should provide the ...