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

Error encountered while attempting to convert a unique custom object to JSON in Jersey

Before jumping to conclusions and marking this question as a duplicate, I want to clarify that I have already explored the solutions provided in A message body writer for Java class not found javax.ws.rs.WebApplicationException: com.sun.jersey.api.Messag ...

Tips for sending Decimal objects to JSON in Django

My question involves a query set that contains Decimal objects. I am trying to pass this data to a JSON dump using the following code: ql = Product.objects.values_list('length', 'width').get(id=product_id) data = simplejson.dumps(ql) ...

Tips for retrieving the ID of a newly added Firestore document in Vue.js

I am currently using Vue.js and Firebase to create a very basic CRUD functionality. One issue I have encountered is that when I create data from a form and send it to the database, there is no document id available for updating my local array of objects. ...

`Proliferating values through constantly changing addition`

I am facing an issue with my code that involves 3 input fields: <div class="row"> <input onblur="calc_basic_amount();" id="rate_basic"></input> <input onblur="calc_basic_amount();" id="qty_b ...

Transform a CSV file into a JSON object containing arrays of numbers

Feeling a bit stuck on this one - any guidance would be greatly appreciated! Using primarily an online converter, or perhaps even a node package, I am attempting to transform a CSV file structured like so: Cat,31.2,31.2 Dog,35,1 Tree,32.4 into the follo ...

Tips for customizing the border of an outlined TextField in MUI

Below is the current configuration of a TextField component: const styles = { resize: { fontSize: '50px', } } const textField = (props) => { const { classes } = props; return ( <TextField valu ...

How do you adapt nested JSON data when editing sub-columns in a Webix datatable?

Within my Webix datatable, I am utilizing multiple columns under a single column header using the colspan property. The table is populated with JSON data that has an Array structure to populate those sub-columns. I have noticed that when I make edits to a ...

Using Vue.js within Cordova platform allows developers to create dynamic

Having trouble integrating a Vue.js app into Cordova. Everything seems to be working fine, except I'm unsure how to capture Cordova events (deviceready, pause, etc.) within my Vue application. Using the Webpack template from vue-cli. This is my file ...

If the PHP variable evaluates to true, then a CJuiDialog in Yii view will open

I am attempting to open the CJuiDialog if the $check value equals true in the view part. <?php if($check==true) { js:function(){$('#dialogDisplay').dialog('open');} } $this->beginWidget('zii.widgets.jui.CJuiDialog', ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Ways to adjust the color of individual elements within an array

I am currently working on developing a sorting Visualizer using React. My focus right now is on implementing BubbleSort. Below is the structure of my program: https://i.sstatic.net/3TKqe.png Below is the code snippet I have written for this task: class S ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

AJAX: Enhancing Web Pages without Replacing JavaScript

After attempting to replace a section of javascript on my webpage using AJAX, I encountered an issue where it would not replace the content. When I checked the element with the id 'treintracking', I could see the javascript code from the script b ...

Can media queries styles be applied to a window of random size using JavaScript?

Can JavaScript be used to apply media queries style based on random window sizes? I have 5 buttons that I want to switch styles for using JavaScript according to the media queries defined in my CSS stylesheet. Is there a method to achieve this? ...

Specify touch event regions with the ngTouch directive

I recently implemented ngTouch in my AngularJs web app to detect swipe left and right gestures. I am using this feature to open and close a side bar menu. Currently, the swipe events are linked to the entire wrapper like this <div ng-style="body_st ...

Next.js presents a challenge with micro frontend routing

In the process of developing a micro frontend framework, I have three Next.js projects - app1, app2, and base. The role of app1 and app2 is as remote applications while base serves as the host application. Configuration for app1 in next.config.js: const ...

What is the functionality of the save callback in Mongoose?

Currently in the process of learning about Mongoose's save() function for the MEAN stack. This particular function requires a callback as outlined in its API documentation: Model#save([options], [fn]) Saves this document. Parameters: [options] < ...

Conceal dynamically generated div elements created with ngIf

I am currently working on initializing this div using ngOnInit in Angular ngOnInit(): void { let optTemp = ''; for (let data of arrOption) { optTemp = optTemp + '<option>' + data.trim() + '</option> ...

Transferring PointLight Parameters to a Custom Shader using three.js

I am looking to achieve a similar effect as the undulating sphere demonstrated in the Aerotwist Tutorial. Instead of using a fake GLSL hard-coded light like in the tutorial, I am interested in passing information from a three.js PointLight instance to my s ...

Comparison of WebAPI Response Codes: Understanding the Difference Between 401 and

As a part of my learning project, I am developing a WebAPI and striving to implement best practices. The initial focus is on creating an authentication API that accepts an authentication object in JSON format: { username: myusername, password: mypa ...