Using Backbone to Retrieve a JSON File from a Server: Deciding Whether to Include the File Extension ".json" in the URL or URLRoot

Exploring Backbone with exercise by trying to obtain a JSON file from the server using the urlRoot property of the Model.

Encountered an error (404) when setting urlRoot: "./js/json/todo", paths with ".json" work but

console.log(todoItem.get('description'))
returns undefined.

In most Backbone applications, omitting the extension .json seems common e.g. urlRool: "/todos" rather than urlRoot: "/todos.json", yet errors are experienced without the extension.

  • Seeking guidance on correct use of url and urlRoot properties.
  • Interested in learning about implications of not using .json or including it.
  • Lastly, seeking feedback on whether the JSON file format below is suitable for Backbone?

Backbone:

(function(window, $, Backbone) {
    var TodoItem = Backbone.Model.extend({ urlRoot: './js/json/todos' });

    var todoItem = new TodoItem({id: 1});

    todoItem.fetch();

    console.log(todoItem.get('description')); // Returns undefined

}(window, jQuery, Backbone));

JSON:

{
    "todos": [
    {
        "description": "Pick Up Milk",
        "status": "incomplete"
    },

    {
        "description": "Do shopping at Market",
        "status": "incomplete"
    }]
}

Answer №1

The reason why you see it without the .json extension is because the backend of the website is configured to return JSON data without the .json extension in the URL. When working with a static JSON file, you simply need to add .json to the file name.

It ultimately depends on how the server is set up and what is handling the URLs.

In terms of formatting, there is no need for the curly braces {}. It can be formatted as follows:

[{
    "description": "Pick Up Milk",
    "status": "incomplete"
},

{
    "description": "Do shopping at Market",
    "status": "incomplete"
}]

When using a static JSON file, I handle the GET request manually like this:

$.ajax("./js/json/todo.json").done(function(data) {
    // Here, I am using extend to add an id, but you could also just use data[0]
    var todoItem = new ToDoItem(_.extend(data[0], { id: 1 }));
}

If your JSON file contains a collection of items, Fetch may not work effectively. Instead, you can create a Backbone Collection like this:

var ToDoCollection = Backbone.Collection.extend({
    model: ToDoItem,
    url: "./js/json/todo.json"
});
var toDos = new ToDoCollection();
toDos.fetch();

This approach should provide you with a collection where each entry corresponds to a model in the JSON file.

Answer №2

It is irrelevant whether you are utilizing .json or not, as long as the endpoint exists. Therefore, if your file is named todo.json, it must contain .json. A simple method to verify this is by copying and pasting the file's URL into your browser and ensuring it displays correctly.

The reason for receiving undefined may be due to the structure of your JSON file. At the top level of the object, there is no description. Backbone anticipates an array of Models, not an object that holds an array of Models. For instance:

[{
    "description": "Pick Up Milk",
    "status": "incomplete"
},
{
    "description": "Do shopping at Market",
    "status": "incomplete"
}]

url pertains to a collection, while urlRoot pertains to an individual model. This allows for the creation of a logical naming convention. For example, when accessing an API, I might use the following framework:

GET /todos - Retrieve all todos
GET /todo/:id - Retrieve one todo

This can be achieved by defining the url as /todos and the urlRoot as /todo. Backbone will automatically attach the ID. It is important to note that while urlRoot is optional, url must be specified.

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

The value in the textarea will stay unchanged even after the form has been submitted

I recently resolved my previous issue, but now I am seeking advice on how to prevent a textarea from clearing its input after submitting a form. You can view the jsFiddle here: http://jsfiddle.net/rz4pnumy/ Should I modify the HTML form? <form id="for ...

When I hover over div 1, I am attempting to conceal it and reveal div 2 in its place

I need help with a CSS issue involving hiding one div on mouse hover and showing another instead. I attempted to achieve this using pure CSS, but both divs end up hidden. Would jQuery be necessary for this task? Below is the CSS/HTML code I wrote: .r ...

Changing HTML elements dynamically within an ng-repeat using AngularJS directives

I have devised an angular directive where I execute an ng-repeat. The fundamental purpose of this directive is to interchange itself with a distinct directive that depends on a value forwarded into the original directive: <content-type-directive type=" ...

Encountering a critical issue with Angular 12: FATAL ERROR - The mark-compacts are not working effectively near the heap limit, leading to an allocation failure due

After upgrading my Angular application from version 8 to 12, I encountered an issue. Previously, when I ran ng serve, the application would start the server without any errors. However, after updating to v12, I started receiving an error when I attempted t ...

Whenever I attempt to include additional drop-down lists, jQuery fails to function

My webpage features multiple drop down lists, with one populating based on the selection from another. Additionally, I have included a button at the bottom of the page. When this button is clicked, I need to add another column to the page. However, after ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

Can you explain how to utilize prop values for setting attributes in styled-components v4 with TypeScript?

Overview Situation: const Link = styled.a` border: solid 1px black; border-radius: 5px; padding: 5px; margin: 10px 5px; `; type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement>; const LinkAsButton = styled(Link).attrs<ButtonP ...

Creating a table and filling it with data from any cell is a simple process

I have a question about creating an HTML table similar to the image shown here: image I want to populate the table with data from a JSON response received from a web service: { "ErrorCode": 0, "ErrorMessage": "ok", "Data": [ { ...

What is the best way to pass JSON data into a JavaScript function?

As a beginner in javascript, I have been struggling to find a solution for my problem for a week. The code example I am working with is shown below (all within an HTML page in the head tag) //example function 1 function randomString(len, charSet) { ...

Best Practices for Installing Webpack in a Client/Server Folder Structure

Working on a React Nodejs web application and in the process of figuring out how to bundle the frontend using webpack. This is how my project's structured: Where exactly do I need to install webpack and configure webpack.config.js? I've noticed ...

Issue with PHP form not saving data and correctly parsing output

I am facing an issue with my PHP page where it is supposed to grab responses from a form, insert the data into a table, and then display the response on the same page. I am using ajax to send form values without refreshing the page, but unfortunately, no i ...

The JavaScript for loop using .appendChild() is inserting the values of the final object, represented as [object object], into the HTML document

$(document).ready(function () { GetDetails(); }); function GetDetails() { let albumlist = document.getElementById("album-list"); $.ajax({ url: '/Store/browseajax', type: 'GET', data: { id: '@ ...

Utilizing 'document.execCommand' for handling 'delete' key events in AngularJS

Here is a demo plunkr link that I have created to demonstrate the issue. I am looking to implement the strikeThrough command whenever there is a delete operation. For instance: If the user selects "Text" and presses the delete or backspace key, it should ...

Secure User Validation Using ExpressJS and CouchDB

I am currently working on implementing a CouchDB User login into my express app using a frontend form and storing the login information in the session. Here is what I have done so far: In my app.js file: var express = require('express'); var co ...

Implementing a change event upon setting a value to an input element using JavaScript

My plan is to develop a Chrome extension that can automatically fill passwords. The code for this functionality looks like the following: //get the account document.querySelector("input[type=text]").addEventListener('input', () => { ...

Ways to prevent image toggling when the mouse moves out of it or when the hover effect stops

I'm looking to toggle between two images on mouseover/hover and stop the toggling when hovering stops. Here is the HTML code I have: <div class="fader"> <img src="image1" /> <img src="image2" /> </div> This is the JQuery ...

Tips on parsing JSON data with Python

I am currently working with a module that provides data in the following format: j = ("{u'auth_user': {u'first_name': u'a', u'last_name': u'b', u'uid': u'x', u'timezone_offset&apos ...

Generating a JSON Object by combining elements from multiple arrays

I need assistance in creating a single Json object from two arrays using JavaScript or jQuery. The data is stored in the database in the format shown below: clob_field_1: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 etc etc ... clob_field_2: 8106.23, 7856.49, 8009.15, ...

Function wrapper intended for axios

How can I create a wrapper function for axios? I am looking to create a function that can return axios, allowing for easy substitution with another fetch API in the future. This is what I have attempted so far: import axios from 'axios' expor ...

Managing the Response from Google Geocode API in a Vue JS Component

I am facing an interesting challenge. I have a scenario where users can choose between two options - using their current location or entering a zip code. When a user inputs a zip code, I need to make a call to the Google geocode API to retrieve the central ...