I have a Web API and I'm trying to get JSON Data from it by using Vue, but I get neither data or errors, so I don't what is wrong. I want to load the data when the page is loaded.
Here is my code:
const v = new Vue({
el: '#divContent',
ready: function () {
this.loadData();
},
data: {
content: 'loading',
serverData: null
},
methods: {
loadData: function (viewerUserId, posterUserId) {
const that = this;
$.ajax({
contentType: "application/json",
dataType: "json",
url: "http://my-webapi/",
method: "Post",
success: function (response) {
that.$data.serverData = response;
},
error: function () {
alert('Error')
}
});
}
}
});
My HTML
<div id="divContent" class="content">
{{ content }}
</div>
Yes you can use jQuery’s $.ajax() API. However, using jQuery just for making Ajax calls is not recommended. You don’t want to include the whole jQuery library just for the purpose of using Ajax, do you? :-)
For Vue.js, you have quite a few options for using Ajax, such as:
Here is an example of using the Browser's fetch API.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
</head>
<body>
<div id="divContent">
<h1>Article Search Results</h1>
<form v-on:submit.prevent="search">
<input type="text" v-model="query">
<button type="submit">Search</button>
</form>
<ul>
<li v-for="article in articles" v-bind:key="article.source + article.id">
{{ article.title }}
</li>
</ul>
</div>
</body>
</html>
const vm = new Vue({
el: '#divContent',
data() {
return {
query: 'gene',
articles: 'loading'
}
},
created() {
this.search();
},
methods: {
search: function () {
fetch(`https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=${this.query}&format=json`)
.then(response => response.json())
.then(json => {
this.articles = json.resultList.result;
});
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With