简体   繁体   English

Javascript-在页面加载中包括.txt文件的内容*没有* ajax吗?

[英]Javascript - Include contents of .txt file on page load *without* ajax?

The Skinny 瘦的

I'm well aware that JS requires AJAX (or some synch/asynch call) to get the contents of a file after page load . 我很清楚,JS需要AJAX(或一些synch / asynch调用)才能在页面加载后 获取文件的内容

(From previous link) (来自上一个链接)

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();

Browsers won't allow direct access to files. 浏览器不允许直接访问文件。 This is for security reasons, mitigating XSS attacks and so forth. 这是出于安全原因,减轻了XSS攻击等。

But is there a way to include it on page load... without including it into the markup? 但是有没有一种方法可以将其包括在页面加载中...而无需其包含在标记中?

I am using a couple client-side templates (not interested in client- vs server-side debate). 我正在使用几个客户端模板(对客户端与服务器端的辩论不感兴趣)。 Currently, the only way to include them on page load, without additional calls to the server, is to toss the contents into a custom-type script tag: 当前,在不进行服务器额外调用的情况下 ,将它们包括在页面加载中的唯一方法是将内容扔到自定义类型script标签中:

<script id="t1" type="x-some-template">
    ... contents of template
<script>

And then reference the contents of the script block in some way: 然后以某种方式引用脚本块的内容:

var templateContents = $('#t1').html();

But if the template is long, it muddies up the markup (assuming the user is viewing the source). 但是,如果模板很长,则会混淆标记(假设用户正在查看源代码)。 This is entirely aesthetics and nit-picking, and does not affect how anything operates , but is there some sneaky way of including the templates without having them appear in the markup? 这完全是美学和挑剔,并且不影响任何操作 ,但是是否存在一些偷偷摸摸的方式来包含模板而不将其出现在标记中?

So Far... 至今...

I tried putting the template into its own .js file, and including it in the same way: 我尝试将模板放入其自己的.js文件,并以相同的方式包括它:

<script id="t1" type="x-some-template" src="t1.js"><script>

But then there is no way to reference the content, since it is never loaded by the browser. 但是,由于无法从浏览器加载内容,因此无法引用该内容。

(From javascript.info ) (来自javascript.info

If you put an unsupported value into type, eg , the contents will be ignored. 如果将不支持的值输入类型,例如,则内容将被忽略。 This is a trick used add data that was not rendered to the page. 这是用于添加未呈现到页面的数据的技巧。

But if you put in a known type: 但是,如果输入已知类型:

<script id="t1" type="text/javascript" src="t1.js"><script>

An error will be thrown, since the contents of the file isn't in proper JS. 由于文件内容不在正确的JS中,因此将引发错误。

Other solutions could be assigning the template content to a JS variable, and including the external file, then referencing said variable: 其他解决方案可能是将模板内容分配给JS变量,并包括外部文件,然后引用所述变量:

// t1.js

var temp = `... contents of template... `;

// page.html

var templateContents = temp;

But even with the template literal , it can be a nightmare including complex templates. 但是,即使使用模板文字 ,也可能是包含复杂模板的噩梦。 And then you have the issue of assigning each template to a different variable and tracking them all. 然后,您遇到了将每个模板分配给不同变量并跟踪所有变量的问题。 Headaches abound. 头痛比比皆是。 The problem would be mitigated slightly if you could assign each template to a standard variable, and then reference them based on the script block that included it... 如果您可以将每个模板分配给一个标准变量,然后根据包含它的脚本块对其进行引用,则可以稍微缓解该问题。

var templateContents1 = $('#t1').temp;
var templateContents2 = $('#t2').temp; // Or something like this...
... 

But that's a no-go. 但这是不行的。

I've search high and low, but all I've come across is endless AJAX, and HTML Imports , which have awful support . 我一直在搜寻,但我遇到的只是无尽的AJAX和HTML Imports ,它们都提供了强大的支持

Finally, The Question 最后,问题

Has anyone stumbled across a beautiful way to do this? 有谁偶然发现了一种漂亮的方法来做到这一点? And in a browser-independent (ie universally supported) way? 并且以与浏览器无关的方式(即普遍支持的方式)进行? I want to stay away from any post-load server calls (ie, AJAX). 我想远离任何加载后服务器调用(即AJAX)。

Load the page with the content, and use it persistently. 加载页面内容,并永久使用它。

Thoughts On Potential Solutions 关于潜在解决方案的思考

The only way to beautify the markup (that I can come up with) is to use the currently-working method, and then completely remove the script block: 美化标记(我可以提出)的唯一方法是使用当前正在使用的方法,然后完全删除脚本块:

var templateContents = $('#t1').html();
$('#t1').remove(); // Or similar

But this isn't a very good solution, 'cause then the content is no longer available if JS decides to garbage collect on templateContents , and you have to re-load the template. 但这不是一个很好的解决方案,因为如果JS决定对templateContents进行垃圾回收,那么内容将不再可用,而您必须重新加载模板。

I'm not much for server/.htaccess stuffs, but maybe I can modify the .htaccess (or similar) to read the custom-type script as plain text, and then it persists in memory to use on an as-needed basis? 我对服务器/.htaccess的东西不多,但也许可以修改.htaccess(或类似内容)以将自定义类型的脚本读取为纯文本,然后将其持久保存在内存中以根据需要使用?

Golly, it sure would be swell if... 天哪,如果...

The ideal situation would be similar to how I described above, where the plain template content is in a separate file (without being assigned to a variable)... 理想的情况将与我上面描述的类似,原始模板内容位于单独的文件中(未分配给变量)。

// t1.js

... all the contents of the template...

And then including it in a single, beautiful line... 然后将其包含在一条漂亮的线条中...

// page.html

<script id="t1" type="whatever-works" src="t1.js"></script>

And reference the template contents in an equally simple and beautiful line... 并以同样简单美观的方式引用模板内容...

var templateContents = $('#t1').someTextAccessMethod();

Any thoughts? 有什么想法吗?

You can try this. 你可以试试看

Here is exactly what I did. 这正是我所做的。

main.html

<!DOCTYPE HTML>
<html>

<head>
   <title>load txt</title>
</head>   
<body>
   <script type="text/javascript" src="test.js" type="application/json">
   </script>
   <script>
       document.write(a.data);
   </script>
</body>

</html>

And the test.js file. 还有test.js文件。

var a = {
    "data" : "All the content of .txt file here with proper escape sequence and other formatting stuff"
  }

Now, Explanation. 现在,解释。

You can put all your data in txt file in a object. 您可以将所有数据放在一个对象的txt文件中。 Save that object in a variable and in a seperate file. 将该对象保存在变量和单独的文件中。 You can use script tag to load that file during inital page load. 您可以使用脚本标记在初始页面加载期间加载该文件。

Use type="application/json" to stop the browser from performing any checks on the content of object. 使用type =“ application / json”阻止浏览器对对象的内容执行任何检查。

The extension of the file can be anything you want. 文件的扩展名可以是任何您想要的。 because the browser just checks the type of script being downloaded. 因为浏览器只检查正在下载的脚本的类型。

And once you have loaded the txt file wrapped in a object you can do JSON.stringify , load it into localStorage and then remove the script tag from html. 并且,当您将包装JSON.stringify txt文件加载到对象中后,您可以执行JSON.stringify ,将其加载到localStorage ,然后从html中删除script标签。

After this it'll be accessible even if you close the website and reopen it. 之后,即使您关闭网站并重新打开它,也可以访问它。 And you don't have to modify anything on the server side or client side. 而且您不必在服务器端或客户端修改任何内容。

I see that you have no problem with putting the contents on a <script> tag except that its making your markup/view source dirty. 我看到您将内容放在<script>标记上没有问题,除了它会使标记/视图源变脏。 So why not smartly pour your file content onto an external JS file(host it somewhere/locally) & then in your project call that external script , something like: 那么,为什么不聪明地将文件内容倒入外部JS文件(在某个位置/本地托管),然后在您的项目中调用该外部脚本 ,例如:

<script type="text/html" src="http://yourdomain.com/contents_of_template.js">
    var t1 = "<div> template contents here </div>"
</script> 

Basically this way you will get the contents and at the same time the contents of the file cannot be seen on your viewsource since its part of another external JS file . 基本上,通过这种方式,您将获得内容,同时,文件内容也无法在视图源上看到,因为它是另一个外部JS文件的一部分 Let me know if this makes sense to you. 让我知道这对您是否有意义。

You could also explore options like window localStorage or FileAPI to read & write files, but again both would require some way of the reading the contents via AJAX or so. 您还可以浏览诸如localStorageFileAPI窗口之类的选项来读取和写入文件,但是同样,这两者都需要通过AJAX读取内容的某种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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