What is the best way to retrieve information from a web service using Vue.js within an HTML environment?

I'm trying to retrieve data from a web service using vue.js, but I'm having trouble fetching the data. Can I use vue.js without installing node.js? Any help would be appreciated. Thank you in advance.

<!DOCTYPE html>
<html lang="en>
<head>
<title> </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="76000313364458465845">[email protected]</a>/dist/vue.js "></script>   <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="04727161297661776b7176676144352a342a37">[email protected]</a>/dist/vue-resource.min.js"></script>        
</head>
<body>
     <div id="app">             
        <table border=1>
           <thead>
             <tr>
             <th> title</th>
             </tr>
            </thead>
             <tr id="app">
             <td>{{data.title}}</td>
             </tr>
         </table>           
     </div>
<script type="text/javascript">
var dataURL = 'https://swapi.co/api/films/?format=json';

var App = new Vue({
  el: '#app',
  data: {
    posts: [] // starting with an empty array
  },
  mounted() { 
    var self = this 
    $.getJSON(dataURL, function(data) {
      self.posts = data.results;
    });
  }
})
</script>
</body>
</html>

Answer №1

You've included Vue Resource, but are also using JQuery. For more information, visit: https://github.com/pagekit/vue-resource

I have implemented a v-for loop to iterate through the posts array in your table.

It's important to note that there is no scenario where you would require JQuery while working with VueJS.

<!DOCTYPE html>
<html lang="en>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1365667653213d233d20">[email protected]</a>/dist/vue.js"></script>   <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2d4d7c78fd0c7d1cdd7d0c1c7e2938c928c91">[email protected]</a>/dist/vue-resource.min.js"></script>        
</head>
<body>
     <div id="app">             
        <table border=1>
           <thead>
             <tr>
             <th>title</th>
             </tr>
            </thead>
             <tr v-for="item in posts">
             <td>{{item.title}}</td>
             </tr>
         </table>           
     </div>
<script type="text/javascript">
var dataURL = 'https://swapi.co/api/films/?format=json';

var App = new Vue({
  el: '#app',
  data() {
    return {
      posts: [] // initialize empty array
    }
  },
  mounted() { 
    this.$http.get(dataURL).then(res => {
     this.posts = res.body.results
    });
  }
})
</script>
</body>
</html>

Answer №2

Seems like the $ symbol is not defined. My best guess is that it pertains to jquery ? https://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success

I also addressed a few other issues. This solution is functional for me.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9c9f8faad8c4dac4d9">[email protected]</a>/dist/vue.js"></script>   <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295f5c4c045b4c5a465c5b4a4c69180719071a">[email protected]</a>/dist/vue-resource.min.js"><script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>       
    </head>
    <body>
         <div id="app">             
            <table border=1>
               <thead>
                 <tr>
                 <th>title</th>
                 </tr>
                </thead>
                 <tr id="app" v-for="(post, index) in posts" :key="index">
                 <td>
                 {{post.title}}
                 </td>
                 </tr>
             </table>           
         </div>
    <script type="text/javascript">
    var dataURL = 'https://swapi.co/api/films/?format=json';

    var App = new Vue({
      el: '#app',
      data() { // data should be a function
        return {
          posts: [] // initialize empty array
        }
        
      },
      mounted() { 
        var self = this 
        $.getJSON(dataURL, function(data) {
          self.posts = data.results;
        });
      }
    })
    </script>
    </body>
    </html>

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

Steps for updating the nested array object using the unique identifier: "id"

Having trouble updating the nested state array in my module where users scan QR codes to update tracking numbers. Currently, I am using react js for frontend and Laravel for backend. Issue: When scanning the QR code, the tracking number is not being set t ...

Ways to determine if a device possesses a specific capability

I am currently in the process of developing a web application and am exploring how to determine the capabilities of an Android device. Is there a central registry or database where I can look up the various capabilities and features of an Android device? ...

Modify the style of a webpage through JavaScript

Need help with calling a JS event based on button presses and changing CSS font styling accordingly for each button? Check out the code snippet below: body { background-image: url("back2.jpg"); background-size: 100% 100%; } ...

Smoothly scroll to the bottom of a dynamically updated div using native JavaScript

I am in the process of developing a chat application and my goal is to achieve a smooth scrolling animation that automatically moves the page down to the bottom of the div when dynamic messages are loaded. <ul id="messages"> <li ...

Implementing a live search feature in Jquery, similar to the filtering capabilities found in Angular JS

How can I implement a filter option for the following HTML code that will dynamically display the input given in real time? <div class="block-parent"> <input type="text" name="search" class="search"> <div class="answer block1" style=" ...

working with json files in node.js

I have encountered an issue with manipulating a JSON file using Node.js. Here is the scenario: { "joe": { "name": "joe", "lastName": "black" }, "matt": { "name": "matt", "lastName": "damon" } } Now, I n ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

The perplexing behavior of RxJS Observables with Mongo Cursors

Recently, I've been working on converting a mongo cursor into an observable using my own RxJS implementation. Despite finding numerous solutions online, I wanted to challenge myself by creating one from scratch. I would greatly appreciate it if someo ...

Encountered the error message "Router.js file throwing a TypeError: next is not a function" while implementing navigation guards in my Vue 3 project

I'm puzzled as to why 'i' doesn't recognize the next function, even though I followed a similar video that implemented it without any errors. import Dashboard from "./Pages/Dashboard.vue"; import Customers from "./Pages/Customers.vue"; ...

Updating the placeholder text of a textarea using a conditional statement in PHP

I currently have a textarea within a form that is being outputted: <textarea id='textarea' name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea> ...

Why must I handle Access-Control-Allow-Origin issues with XMLHttpRequest() but not with forms?

When attempting to make a request using XMLHttpRequest(), I encounter the Access-Control-Allow-Origin error. However, when I use a form like the one below, no issues arise. Is there something about forms that allows access? What could be the reason for t ...

After refreshing, Angular route using html5Mode leads to a 'Page Not Found' error page

I have created several Angular routes as illustrated in the code snippet below. app.config(function($routeProvider, $locationProvider, $provide) { $routeProvider .when('/', { templateUrl: 'home.html', controll ...

Directive for displaying multiple rows in an Angular table using material design

I am attempting to create a dynamic datatable with expandable rows using mat-table from the material angular 2 framework. Each row has the capability of containing subrows. The data for my rows is structured as an object that may also include other sub-ob ...

Is there a more efficient alternative to `[].push.apply(this, arr)` for combining elements in an array instance within a constructor?

It only takes 0.15ms for this line in my constructor function to execute. [].push.apply(this, selector); I'm not satisfied with the 0.15ms execution time. I believe there must be a quicker alternative available. This particular line seems to be conv ...

Angular 2 FileReader: A comprehensive guide

I have a situation where I need to upload an image in section X and pass the base 64 data of the uploaded image to section Y. But I am encountering some difficulties in section X HTML: <input type="file" id="hotspot" (change)="uploadHotSpot($event)"&g ...

Basic inquiry about Ajax

Would you like to know a simple solution for refreshing a specific area of your website using ajax? Instead of having JavaScript constantly checking for changes on the server, is there a way for the server to send data when a certain event occurs? Imagine ...

Steps to make a pop-up window for text copying by users

On my website, I have a link that users need to copy for various purposes. I want to provide an easy way for them to see the link and then manually copy it to their clipboard. Instead of using code to copy to the clipboard, I am looking for a solution whe ...

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

The response from the node is not accurate

In the index.js file, I have the following code snippet: function Answer(value) { this._val = value; } Answer.prototype.get = function get() { return this._value; } var lifeAnswer = new Answer(42); console.log(lifeAnswer.get()); var piAnswer = new ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...