Using a local file as a data source in JavaScript

前端 未结 6 947
星月不相逢
星月不相逢 2020-12-12 17:36

Background:

I want to make an \"app\" that uses JavaScript/HTML only and can be opened by a browser directly from the filesystem. This app

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 18:12

    Here is an example that uses JSON data in an external file that works locally or on a server. This example just uses the browser's language setting to load a < script > with localized html and then processes its json object to reset the data in the indicated tags with localized content

    
    
    
    
    
    
    This is the default text of string1.
    This is the default text of string2.

    The data files for this look like:

    items=[
    {"id":"string1","value":"Localized text of string1."},
    {"id":"string2", "value":"Localized text of string2."}
    ];
    

    but you can use any parameter to conditionally load the appropriate file (it will be inserted as the first tag in < head >, so it will be usable in anywhere) and the JSON format is capable of handling a large variety of data. You may want to rename the function setLang to something more appropriate and modify it to meet your needs such as ... for each i add a row, then add fields with the data (it looks like you already have a handle on that part) and your JSON would look like:

    items=[
    {"fname":"john","lname":"smith","address":"1 1st St","phone":"555-1212"},
    {"fname":"jane","lname":"smith","address":"1 1st St","phone":"555-1212"}
    ];
    

    if you need to preprocess your data, awk is pretty handy - it would be something like: (untested guestimate)

    awk 'BEGIN{FS=",";print "items=[\n"}
    {printf "{\"fname\":\"%s\",\"lname\":\"smith\",\"address\":\"1 1st St\",\"phone\":\"555-1212\"},\n", $1, $2, $3, $4}
    END{print "];"}' file.csv > file.js
    

    Edit: now that OP is more clear, only mozilla browsers allow XMLHttpRequest on file:// out of the box and chrome (possibly other webkit based browsers) can be configured to allow it. Knowing that it may NOT work on IE<10, you can:

    var filePath = "your_file.txt";
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET",filePath,false);
    xmlhttp.overrideMimeType('text/plain');
    xmlhttp.send(null);
    //maybe check status !=404 here
    var fileContent = xmlhttp.responseText;
    var fileArray = fileContent.split('\n')
    var n = fileArray.length;
    //process your data from here probably using split again for ','
    

    I'm leaving the initial json-p variation for others that may have a similar issue, but have some control of their data format, since it will work on all javascript capable browsers. However, if anyone knows a way to make it work for IE (other than running a small web server), please edit.

    Edit 2:

    With mozilla browsers you can also use iframes

    
    
    
    
    
    
    
    
    

提交回复
热议问题