Accessing a JSON file stored locally using JavaScript

I am trying to access a .json file from my localhost, but I am encountering some issues!

The contents of this file are shown below:

[
 {"source":"tw1", 
  "text":"fubar"}, 

 {"source":"tw2", 
  "text":"foo"}
]

To set up my localhost, I used the command: python -m http.server 8888 &, which you can find more information about in the D3.js documentation.

Below is the javascript code that I have written:

<script type="text/javascript" src="lib/jquery-1.9.1.js"></script>
   <script>
    $(document).ready(
        $.getJSON("http://localhost/test.json", function(data){
            document.write(data);

    });
    </script>  
 

Answer №1

If you decide to open your server on port 8888, remember that you need to request it on that specific port:

$.getJSON("http://localhost:8888/test.json", function(data){

It's important to note that the server must have the appropriate CORS headers set in order to bypass any cross-domain restrictions. You can learn more about this from this resource.

Another issue seems to be a compilation error in your code, indicated by the missing });. The indentation inconsistency highlights this problem:

$(document).ready(
    $.getJSON("http://localhost:8888/test.json", function(data){
        document.write(data);
    }); // <=== was missing
});

In addition, using document.write after the page loads is not recommended. Instead, consider utilizing DOM manipulation methods such as

$(document.body).append($('<pre>'+data+'</pre>'));

Answer №2

It appears the issue lies in your attempt to retrieve the json file from your local computer. To resolve this, consider uploading your json file to an online server and accessing it from there rather than relying on the one stored on your computer.

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

Submitting a form using an anchor tag in Angular 8: A step-by-step guide

I have a question about how to submit form data using hidden input fields when a user clicks on an <a> tag. <form action="/submit/form/link"> <input type="hidden" [attr.value]="orderNumber.id" /> <input type="hidden" [attr.value]= ...

Start a Draft.js Editor that includes an unordered list feature

I am trying to pre-populate a draft.js editor with an unordered list made from an array of strings. Here is the code I have so far: const content = ContentState.createFromText(input.join('*'), '*') const editorState = EditorState.crea ...

Using HTML and CSS to create a Contact Form

Greetings! I have come across this contact form code: /* Custom Contact Form Styling */ input[type=text], [type=email], select, textarea { width: 100%; padding: 12px; border: 1px solid #555; margin-top: 6px; margin-bottom: 16px; resize: v ...

Utilizing Query Data Source in ASP.NET MVC for Enhanced JQuery DataTables Experience

Overview I am venturing into ASP.NET from ColdFusion and seeking guidance on replicating a similar technology in MVC 5. My current approach involves running a query in a CFC to populate a DataTable, where the results are then arranged in JSON format and ...

Tips for accessing the following element within an array using a for loop with the syntax for (let obj of objects)

Is there a way to access the next element in an array while iterating through it? for (let item of list) { // accessing the item at index + 1 } Although I am aware that I could use a traditional for loop, I would rather stick with this syntax. for (i ...

Guide on transferring binary image data to a JavaScript function

I have $comment->image_data as the binary data of the image and I want to pass this data to the imgclick() function. Attempting the method below, but encountering an unexpected token error. <img src="data:image/jpg;base64,'.$comment->image_t ...

Encountering Type Error in React Native when making HTTPS request with JSON body on Android: Network request failure

Encountering a network issue specific to React Native - all https/http requests with a json body result in TypeError: Network request failed This issue is isolated to Android only, as everything is functioning properly on iOS and for all other requests wi ...

filtering the properties of mongoose documents

I have created a schema as shown below: var UserSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, email: { type: String, required: true }, location: { type: String, required: true }, p ...

An effective method for appending data to a multidimensional array in Google script

Is there a way to expand a multidimensional array of unknown size without relying on a Google Sheets spreadsheet to manage the data? I've searched everywhere but can't find an example for a 3-dimensional array. Here's the challenge I'm ...

What is the process for managing cookies on the server side using Node.js?

I have been struggling to access cookies on the server side and have not attempted anything yet. Is there a specific method or NPM package that can assist in setting or retrieving cookies on the server side? ...

Is there a YUI Custom Event available for pre-selecting the value in a Dropdown

Imagine a scenario where I have a dropdown field that automatically selects a value as soon as it is rendered (for example, a Country field in a signup form). This dropdown interacts with other components, causing the selected value to change dynamically. ...

An effective way to determine the size of a browser through javascript

In an effort to enhance the responsiveness of a website, I have included the following code snippet on one of my pages: document.write(screen.width+'x'+screen.height); However, I am encountering an issue where the code displays my screen resolu ...

What is the best way to transfer Flow type properties from one React component to another?

I'm in the process of developing a component that will wrap another component known as Button. The tricky part is that the library where Button is defined does not expose the type of its properties. In order to properly assign types to my component, ...

Selecting a pair of radio buttons to toggle the visibility of different div elements using JavaScript

I've been working on two radio button categories that control the visibility of different input fields. I'm making progress, but I'm still struggling to get it to work perfectly. Below are the images for reference: The combination of &apos ...

This error message 'React Native _this2.refs.myinput.focus is not a function' indicates that

When working with React-Native, I encountered a specific issue involving a custom component that extends from TextInput. The code snippet below demonstrates the relevant components: TextBox.js ... render() { return ( <TextInput {...this.props} ...

Displaying multiple images on the face of a cylinder using three.js

I am struggling to showcase multiple images on the outer surface (not the top or bottom) of a rotating cylinder using three.js. I have managed to display one image successfully, but my objective is to exhibit several side by side. Despite adding three text ...

Strategies for modifying state in reactjs

My chat application, built using reactjs, nodejs, and mongodb, is experiencing an issue. Although I am storing data in mongodb and adding single messages to the 'messages' array, the chat app does not display these messages. It seems that even be ...

AJAX successfully completes, but no response is received

I've been struggling to get the success function in my AJAX call to trigger. I know everything is set up correctly because when I make a request to my API, I can see that it's hitting the URL and the server is responding with an HTTP 200 status. ...

Experiencing difficulties while attempting to authenticate gcloud using a json file

I am facing an issue with using the gcloud docker image to authenticate and access gcloud. The error message I am receiving is as follows: ERROR: (gcloud.auth.activate-service-account) Could not read json file credentials.json: Invalid control character ...

Having trouble getting @vercel/ncc to work, keeps throwing a "Module not found" error

Recently, I have been attempting to follow a tutorial on creating custom GitHub actions using JavaScript from here. The tutorial suggests using the @vercel/ncc package to compile code into a single file if you prefer not to check in your node_modules folde ...