What is the best way to display text from a file on a different html page using jQuery's json2html?

Here is the json data:

var data = [
        {
            "name": "wiredep",
            "version": "4.0.0",
            "link": "https://github.com/taptapship/wiredep",
            "licensePath": "/licenses/wiredep"
        }
    ];
    

This html code renders the json on a webpage:

var transform = {"<>":"li","html":[
        {"<>":"span class='name'","html": [{ "<>":"a", "href": " ${link}", "html": " ${name}"}]},
        {"<>":"span class='vers'", "html":" ${version}"}, 
        {"<>":"div","html":" ${licensePath}"}
        ]};
        
        $(function(){
            // Create the list
            $('#list').json2html(data,transform);
        });
    

The file at /licenses/wiredep contains licensing information that I want to render in the HTML page instead of just showing the path.

Desired final output:

Name: wiredep

Version: 4.0.0

License Path content:

The MIT License (MIT)

Copyright (c) 2014 Stephen Sawchuk

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Answer №1

When using JSON2HTML, it is important to note that it does not handle file paths automatically. If you wish to include the contents of a file in the output, you will need to manually add it to the data before passing it to json2html().

The question then arises: "How can I retrieve the text of a file based on its path in javascript?". The answer is simpler than you might think. If you are already utilizing jQuery, a solution using jQuery.get() can be implemented, although it is also achievable without jQuery.

The process involves two steps: firstly, initiating a request to the server to fetch the file content. This can be achieved by using jQuery.get() as follows:

$.get('/licenses/wiredep');

Following this, you must wait for the server to respond with the requested file content. By attaching a callback function to the request, you can handle the response accordingly. In this case, focusing on a successful response, the .done() callback will be triggered:

$.get('/licenses/wiredep').done(function(data) {
  console.log('Contents of /licenses/wiredep:', data);
});

Note: It is crucial to acknowledge that this callback is executed asynchronously. Therefore, any code outside of the callback function is not guaranteed to run after the request completes, even if it appears after the request itself.

To integrate this process into your existing code, consider that the data may consist of multiple objects. Ignoring this complexity, you can modify your code as follows:

$.get('/licenses/wiredep').done(function(response) {
  var data = [
    {
      "name": "wiredep",
      "version": "4.0.0",
      "link": "https://github.com/taptapship/wiredep",
      "licensePath": response
    }
  ];

  var transform = {"<>":"li","html":[
                      {"<>":"span class='name'","html": [{ "<>":"a", "href": " ${link}", "html": " ${name}"}]},
                      {"<>":"span class='vers'", "html":" ${version}"}, 
                      {"<>":"div","html":" ${licensePath}"}
                  ]};
  
  $('#list').json2html(data, transform);
});

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

Extract the text and value from an asp.net treeview by utilizing jQuery or JavaScript

On my website, I am using a TreeView controller. I have disabled node selection by setting SelectAction = TreeNodeSelectAction.None as I have the checkbox option enabled. However, this causes an error when trying to access the .href property of the node. T ...

Modifying CSS to ensure compatibility with various browsers

I am curious if it is possible to modify some CSS when viewed in a different browser. For instance, I have this CSS for a flexbox div: .wdFlex { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit- ...

Sort columns using drag and drop feature in jQuery and AngularJS

Utilizing the drag and drop feature of jquery dragtable.js is causing compatibility issues with AngularJs, hindering table sorting functionality. The goal is to enable column sorting by clicking on the th label and allow for column rearrangement. Currentl ...

The Kendo grid and Jquery functionalities seem to be malfunctioning on my View page

Looking to incorporate a progress bar using Jquery UI on my view page. The layout also includes a Kendo Grid component. I included the necessary files (jquery-ui.css, jquery-.js, jquery-ui.js) but encountered an error when adding jquery.js. The error mess ...

jQuery fadeIn effect happening at rapid speed

I am currently working on integrating ajax with WordPress. After the ajax call is completed, I am successfully fading out a specific div slowly. However, when trying to fade in the new data using jQuery's fadeIn() method, I noticed that regardless of ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

Is it possible for me to pass a value through props that is not currently stored in the state?

Within the realm of Reactjs, imagine a scenario where there exists a <Parent> component containing state and a variable named foo, which is either 'global' or local to Parent. The question arises: Can we pass foo as props using <Child v ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

When combining <a> with the class line-through, the line does not appear

I am currently utilizing a class to replace the deprecated strike in HTML: .entfall { text-decoration: line-through; } However, when using Firefox 38.x and the following code: <span class="entfall"><a href="some link">text</a></span ...

"The fascinating world of asynchronous JavaScript: Promises and Del

I've been diving into Promises, but I'm a bit confused by this code snippet. Can you help clear things up for me? const promise = new Promise((resolve, reject) => { console.log('Promise started') resolve('Success') }) ...

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

Creating a custom directive for input validation in Angular

I am currently working on building a basic custom directive in AngularJS to validate if the user input is an integer or not. When the user types in an integer, I want an error message to display at the bottom that states "integers are not allowed". Do yo ...

Difficulty arises when applying hover effects to animations using callbacks

Currently facing an issue with the hover event in jQuery. There are two side-by-side containers with hover events on both. When hovering, a div containing additional information slides up into view and slides back down when the hover ends. The concept is ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

Tips for optimizing the performance of file_get_contents and json_decodeHere are some strategies

Currently, I am in the process of developing a personalized fansite that gathers its information from various APIs using code like this: $newjson = file_get_contents(LINK_TO_JSON_HERE); $newarr = json_decode($newjson); The issue I'm facing is that t ...

Updating the NPM entry point without relying on an index.js file

After successfully publishing a private module to NPM, which contains shared code used by multiple services, I encountered an issue with the transpilation process. Since the code is written in ES6, it needs to be transpiled using Babel before being publish ...

Initiate a file download following the redirection of a user to a new page in NodeJS/Express

Overview I am currently developing a NodeJS project using Express. In the application, there are buttons visible to the public that trigger file downloads. These buttons are linked to protected routes which will redirect users to a login page if they are ...

Angular single-time binding without the need for continuous watching

I'm currently facing a challenge with Angular's one-time binding feature. For instance, when I want to utilize ngIf with one-time binding, it typically looks like this: <div ng-if="::showImage"> <img src="somesource" img-preloader/ ...

What is causing the issue of my oversized images not showing up on GoDaddy?

I recently uploaded my website on GoDaddy and I am facing an issue where some of my small images (sizes: 872 × 546px) are displaying perfectly fine, but the large ones (banners with a size of 2700 × 900px) aren't showing up. Does anyone have ...

Boost Engagement with the jQuery PHP MySQL Like Feature

Seeking assistance in creating a like button with PHP, MySQL, and jQuery. I'm encountering an error but unable to pinpoint its source. Can anyone provide guidance? The project involves two pages: index.php & callback.php INDEX $k = 1; //POST ID $n ...