Receiving JSON using Javascript and vue.js

When attempting to fetch json data in my vue.js application, I use the following code:

  new Vue({
            el: 'body',
            data:{
                role: '',
                company: '',
                list:[],
                created: function() {
                  this.getJson();
                },
                methods: {
                    getJson: function(){
                        $.getJSON('http://domain.dev/data',function(task){
                          this.list = task;
                        }.bind(this));
                    }
                }
            }
        });

However, the result is coming back as null. Strangely enough, when I test the URL using Postman, it returns valid JSON data. What could be the issue here?

UPDATE:

Here is an example of the JSON data (testdata):

{"EmployeeId":1,"RoleId":5,"DepartmentId":6,"InternId":1,"FirstName":"Zoe","LastName":"Altenwerth","Bio":"Quidem perferendis.","email":"example@email.com","LinkedIn":"example@linkedin.com","Gender":0,"password":"$2y$10$bbUlDh2060RBRVHSPHoQSu05ykfkw2hGQa8ZO8nmZLFFa3Emy18gK","PlainPassword":"gr^S=Z","remember_token":"D528C0Ba1Xzq3yRV7FdNvDd8SYbrM0gAJdFUcOBq4sNEJdHEOb2xIQ0geVhZ","Address":"0593 Dallin Parkway Apt. 499\nBotsfordborough, MT 12501","Zip":"21503-","City":"East Janiston","ProfilePicture":null,"BirthDate":"2002-10-13 00:00:00","StartDate":"1995-11-09 21:42:22","EndDate":"2011-01-27","Suspended":0,"created_at":"2016-02-29 12:21:42","updated_at":"2016-03-02 11:53:58","deleted_at":null,"role":{"RoleId":5,"RoleName":"Superadministrator","Description":"Mag administrators toevoegen en bewerken","deleted_at":null,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"},"department":{"DepartmentId":6,"CompanyId":12,"DepartmentName":"com","Description":"Accusantium quae.","deleted_at":null,"created_at":"2016-02-29 12:21:41","updated_at":"2016-02-29 12:21:41","company":{"CompanyId":12,"CompanyName":"Dare, Bailey and Bednar","Logo":null,"Address":"85762 Tabitha Lights\nWest Jettie, AK 20878-2569","Zip":"29601","City":"Traceside","KvKNumber":"84c70661-9","EcaboNumber":"fdee61e3-a22d-3332-a","deleted_at":null,"created_at":"2016-02-29 12:21:41","updated_at":"2016-02-29 12:21:41"}}}

Answer №1

Let's dive into a simple example on how to import external JSON data into your component:

example.json:

{"greetings": "hello"}

index.html:

<div id="app">
    <pre>{{ json.greetings }}</pre>
</div>

<script type="text/javascript">
var app = new Vue({
    el: '#app',
    data: {
        json: null
    }
});
$.getJSON('http://localhost/example.json', function (json) {
    app.json = json;
});
</script>

--- Updated ---

Alternatively, you can utilize the created event:

<script type="text/javascript">
new Vue({
    el: '#app',
    data: {
        json: null
    },
    created: function () {
        var _this = this;
        $.getJSON('http://localhost/example.json', function (json) {
            _this.json = json;
        });
    }
});
</script>

Answer №2

Expanding on @vbarbarosh's response, utilizing the fetch api of the browser:

a.json:

{"hello": "welcome"}

index.html:

<div id="app">
    <pre>{{ json.hello }}</pre>
</div>

<script type="text/javascript">
new Vue({
    el: '#app',
    data: {
        json: null
    },
    created: function () {
      fetch("/a.json")
        .then(r => r.json())
        .then(json => {
          this.json=json;
        });
    }
});
</script>

Answer №3

To properly connect this to the outer function, ensure you bind it there as well.

getJson: function () { ...}.bind(this)

Answer №4

Latest Vue3 Update

const app = Vue.createApp({
    data() {
        return {
            role: '',
            company: '',
            list:[]
        };
    },
    beforeMount() {
        this.fetchData();
    },
    methods: {
        fetchData() {
            $.getJSON('http://website.com/data', (response) => {
                this.list = response;
            });
        }
    }
});

const mountedApp = app.mount('body');

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

Having trouble retrieving information from the JSON data received from the Google Place Search API

I'm encountering an issue with accessing data from the Google Place Search API. I've provided my code below for reference. getData = (keyword, location, country) => { let dataURI = `${URI}${keyword}+${location}+${country}${API}`; var ...

The data-src tags are functioning properly in the index.html file, but they are not working correctly in angular

I'm still learning about Angular and JavaScript, so please bear with me if my questions seem silly. I've been trying to add a theme to my Angular project. When I include the entire code in index.html, everything works fine. However, when I move ...

Utilizing React to implement a search functionality with pagination and Material UI styling for

My current project involves retrieving a list of data and searching for a title name from a series of todos Here is the prototype I have developed: https://codesandbox.io/s/silly-firefly-7oe25 In the demo, you can observe two working cases in App.js & ...

Directing a controller assignment in AngularJS 1.2 via a directive

Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller. Let's look at this scena ...

Tips for transferring a Vuex-stored value to a variable within Vuejs 3 (Quasar 2)

Currently, I have a Vuex store where I am storing a date (referred to as date). In my Vue.js template (using Quasar 2 beta 12), I can easily access this date using {{ date }}. If I make changes to the date in the store, it reflects immediately in the {{ ...

I am seeking a way to conceal text in an HTML document using JavaScript when the browser window width is less than a specified amount, and reveal it when the window width exceeds that value

I attempted to use the window.screen.width method, but it appears that the script only runs once (upon page load). I am seeking a way for the code to run continuously. Below is my JavaScript snippet: var textinSelected = document.getElementById("se ...

Encountering issues with resolving dependencies in webdriverIO

I'm attempting to execute my WebdriverIo Specs using (npm run test-local) and encountering an error even though I have all the necessary dependencies listed in my package.json as shown below: [0-2] Error: Failed to create a session. Error forwardin ...

Tips for monitoring a variable within a Service using a Controller to trigger a modal?

http://plnkr.co/edit/bdHiU0?p=preview When I require a variable that is returned by a service, like the data in InitTickersFactory.returnTickers(), I can easily assign it to vm.tickersObject. However, in the plnkr example provided above, I am simply toggl ...

Excluding form items that are disabled from a request in ReactJS

In my code, I am dealing with a Form section that contains multiple Collapse.Panel sub-sections. Interestingly, the Form.Item elements within collapsed panels are not included in the form values upon submission. However, I have noticed that certain InputNu ...

Discovering the number of intervals running at any given time within the console - JavaScript

I'm having trouble determining if a setInterval() is active or has been cleared. I set up an interval and store it in a variable: interval = setInterval('rotate()',3000); When a specific element is clicked, I stop the interval, wait 10 sec ...

Issue encountered while running the TestCafe Docker Image within a GitLab CI job. Attempting to run automated end-to-end tests on BrowserStack

We are currently attempting to execute end-to-end tests using testcafe on BrowserStack triggered by a gitlab CI job. Unfortunately, an error keeps appearing: Error: spawn /home/user/.browserstack/BrowserStackLocal ENOENT Our approach involves implementin ...

The derived class did not contain the necessary constructor to deserialize an object of Type

There is no argument constructor in the base class and it is not serializable, so I tried using Object During deserialization, an exception was caught which stated: The constructor to deserialize an object of type 'ProjectHttpClientEx' was not ...

What could be causing the "Error - Only secure origins are permitted" message to appear for my service worker?

Whenever I attempt to implement a service worker on my progressive web application page, why does the browser console display this specific error message? ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed JavaScript Code: ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...

Enhance your Vue PWA by utilizing ServiceWorker to efficiently cache remote media assets fetched from an array of URLs

In my PWA development project, I am looking to provide users with the option to download and cache all media assets used in the application. However, the default behavior of PWAs only caches assets when they are requested during app navigation. My goal is ...

Guide to transmitting webcam feed from server to servlet

I am trying to display the webcam connected to my server in a servlet. I have come across suggestions to use getUserMedia();, however, this only captures the user's video webcam feed and not the server's. Is there a way to achieve this? My servl ...

Guide to retrieving targeted JSON information with an identifier (React Hooks)

I am facing an issue where I need to retrieve a specific item from a JSON by using its unique ID, but the function I have created does not seem to return any data. Here is the function in question: export function getPost(id) { return fetch("http:// ...

Leverage the power of React-PDF to smoothly magnify or minimize your

I am working on a ReactJS project where I want to implement zoom in/zoom out functionality. To display PDF files, I am utilizing the react-pdf package in my web application. According to the documentation, there is a scale prop that allows me to adjust the ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...