загрузить файл уценки из каталога http в строку JavaScript - PullRequest
0 голосов
/ 04 мая 2019

Мне нужен код javascript, чтобы прочитать «файл уценки» из моего каталога http и поместить его в строку javascript.Как бы я изменил этот код, чтобы сделать это?

<!-- FILE: index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Markdown TexDollar Reader</title>
    <!--  Javascript setup using node.js: ->
    <!--    C:\demo> npm install mathjax -->
    <!--    C:\demo> npm install showdown -->

    <script type="text/javascript" src="./node_modules/showdown/dist/showdown.js"></script>

    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
            tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
    });
    </script>
    <script type="text/javascript" 
        src="./node_modules/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>

</head>

<body>

    <script>
        converter = new showdown.Converter();

        <!-- FIXME: Instead of setting text string manually from javascript, 
          i  want to load my file 
          in http directory called "markdown.md" into the javascript string text-->
        text      = '# hello, markdown!';
        text += '\nthis is a test';
        text += '\n$$e=mc^2$$';
        html      = converter.makeHtml(text);
        document.write(html);   
    </script>

</body>

</html>

1 Ответ

1 голос
/ 05 мая 2019

Единственный способ загрузить текстовый файл локально без сервера http - это использовать API-интерфейс HTML5 для загрузки файла через диалоговое окно файла, где пользователь выбирает файл уценки для чтения:

<!DOCTYPE html>
<html>
  <head>
    <title>Render "Markdown file with Tex-Dollar" in browser</title>

    <!-- node.js packages required: -->
    <!--     npm install jquery -->
    <!--     npm install showdown -->
    <!--     npm install mathjax -->

    <script type="text/javascript" src="./node_modules/showdown/dist/jquery.js"></script>

    <script type="text/javascript" src="./node_modules/showdown/dist/showdown.js"></script>

    <script type="text/x-mathjax-config">
        MathJax.Hub.Config({
            tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
    });
    </script>

    <script type="text/javascript" 
        src="./node_modules/mathjax/MathJax.js?config=TeX-AMS_HTML-full"></script>


    <script type="text/javascript">
    var reader; 

    function checkFileAPI() {
        if (window.File && window.FileReader && window.FileList && window.Blob) {
            reader = new FileReader();
            return true; 
        } else {
            alert('The File APIs are not fully supported by your browser. Fallback required.');
            return false;
        }
    }

    function readText(filePath) {
        var output = ""; //placeholder for text output
        if(filePath.files && filePath.files[0]) {           
            reader.onload = function (e) {
                output = e.target.result;
                displayContents(output);
            };//end onload()
            reader.readAsText(filePath.files[0]);
        }//end if html5 filelist support
        else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
            try {
                reader = new ActiveXObject("Scripting.FileSystemObject");
                var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
                output = file.ReadAll(); //text contents of file
                file.Close(); //close file "input stream"
                displayContents(output);
            } catch (e) {
                if (e.number == -2146827859) {
                    alert('Unable to access local files due to browser security settings. ' + 
                     'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' + 
                     'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"'); 
                }
            }       
        }
        else { //this is where you could fallback to Java Applet, Flash or similar
            return false;
        }       
        return true;
    }   

    function displayContents(txt) {
        converter = new showdown.Converter();
        html = converter.makeHtml(txt);
        var el = document.getElementById('main'); 
        el.innerHTML = html; //display output in DOM

        MathJax.Hub.Queue(["Typeset",MathJax.Hub, "main"]);

    }   
</script>
</head>

<body onload="checkFileAPI();">
    <div id="container">    
        <input type="file" onchange='readText(this)' />
        <br/>
        <hr/>   

        <h3>Contents of the Text file:</h3>

        <div id="main">
            ...
        </div>
    </div>
</body>

</html>

рендеринг mathjax немного нестабилен при загрузке из уценки ... если кто-нибудь знает, как это исправить.дай мне знать.спасибо.

...