M
M
Maxim Kukushkin2020-06-27 05:45:36
JavaScript
Maxim Kukushkin, 2020-06-27 05:45:36

How in js to read data from a txt file specified by a link in json?

Hello! I'm trying to make a small online store using js and jquery and json.

Json file is a simple directory of files. js file reads it and outputs data to html.
The problem is that product descriptions are very large - several paragraphs, it is inconvenient to insert them simply into json.
I decided to use a link to a text file with a description of this product in json for the description key.
But I don't know how to process this .txt file in js and display the data on the page. Help me please!

Here is the code:

goods.json

{
  "11292" : {
    "name" : "Яблоки",
    "cost" : 12,
    "description" : "texts/11292.txt",
    "image" : "images/apple.png"
  },
  "11294" : {
    "name" : "Лимоны",
    "cost" : 16,
    "description" : "texts/11294.txt",
    "image" : "images/lemon.png"
  },
  "11295" : {
    "name" : "Клубника",
    "cost" : 22,
    "description" : "texts/11295.txt",
    "image" : "images/strawberry.png"
  }
}


eshop.js

function loadGoods() {
    //загружаю товары на страницу
    $.getJSON('goods.json', function (data) {
        //console.log(data);
        var out = '';
        for (var key in data){
            out+='<div class="single-goods">';
            out+='<h3>'+data[key]['name']+'</h3>';
            out+='<p>Цена: '+data[key]['cost']+'</p>';
            out+='<p>Описание: '+data[key].description+'</p>'; //вот здесь нужно обработать файл txt, но как это сделать?
            out+='<img src="'+data[key].image+'">';
            out+='<button class="add-to-cart" data-art="'+key+'">Купить</button>';
            out+='</div>';
        }
        $('#goods').html(out);
    });
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mt. NATS, 2020-06-27
@me4t10

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question