简体   繁体   中英

How can I make js objects' content be pulled in from an html file?

I have a few js objects containing data that I would like to make it so that the owner can modify from an html file.

In other words, the js object lives in its own js file, but I'm afraid the person editing the data in objects may delete/update the actual code...basically I would like to make it idiot proof. So I'm thinking of having the data live in an html file or even a .txt file to make editing super easy.

Basically anything like A1, A2, A3, A4, B1, B2, etc etc etc... I would like those to live in a separate file in the simplest way possible. Any ideas?

Here is a sample of the objects I have:

 var objOne = [ {first: 'A1', second: 'A2', third: 'A3', fourth: 'A4'}, {first: 'B1', second: 'B2', third: 'B3', fourth: 'B4'}, {first: 'C1', second: 'C2', third: 'C3', fourth: 'C4'} ]; var objTwo = [ {first: 'D1', second: 'D2', third: 'D3', fourth: 'D4'}, {first: 'E1', second: 'E2', third: 'E3', fourth: 'E4'}, {first: 'F1', second: 'F2', third: 'F3', fourth: 'F4'} ]; $('.div span').html( objOne[0].fourth + ' >> ' + objTwo[2].third); 
 <div class="div">Element: <span></span></div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Thank you all.

Sergio

That's what jquery is for. You can load a plain text file

$.get('/path/to/file.txt', function(response) {
    var data = response;
}, 'text');

and then parse it in the browser, and insert the result into your HTML. Or you could use Markdown in you user-modified file

$.get('/path/to/file.md', function(response) {
    var data = response;
    var converter = new Showdown.converter();
    var html = converter.makeHtml(data);
    $('.content').html(html);
}, 'text');

and then use a Javascript markdown library (for example Showdown ) to convert it to HTML in the browser.

There are libraries for a number of data formats, to parse them directly in the browser and then insert the ready-made HTML into your page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM