如何访问通过 <script type="text/plain" 检索的纯文本内容src=...>在 JavaScript 中? [英] How to access plain text content retrieved via <script type="text/plain" src=...> in JavaScript?

查看:16
本文介绍了如何访问通过 <script type="text/plain" 检索的纯文本内容src=...>在 JavaScript 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用<script type="text/plain" src="http://..."></script>时,这里的URL是指一个纯文本文件, 有没有办法在 JavaScript 中访问文件的内容?文件被传输到浏览器,但 script 元素的 innerHTML 属性的值没有改变(它仍然是空字符串).检查 DOM 中的元素节点似乎没有发现任何可以找到接收到的内容的属性.

我知道可以改用 XMLHTTPRequest,但我对为什么浏览器以我描述的方式获取数据但似乎不提供任何访问权限的问题感兴趣.

解决方案

首先,HTMLScriptElementtext 属性是访问文本的首选方法内联

When using <script type="text/plain" src="http://..."></script>, where the URL refers to a plain text file, is there a way to access the content of the file in JavaScript? The file is transferred to the browser, but the value of innerHTML property of the script element is not changed (it remains the empty string). Inspecting the element node in the DOM does not seem to reveal any property through which the content received could be found.

I know that XMLHTTPRequest can be used instead, but I’m interested in the problem why browsers fetch data in the way I described but do not seem to offer any access to it.

解决方案

First of all, the textattribute of the HTMLScriptElement is the preferred method to access the text of an inline <script> element. DOM-Level-2 and HTML5: 4.11.1 both indicate that a script should have an attribute text which contains the scripts interior text:

The IDL attribute text must return a concatenation of the contents of all the Text nodes that are children of the script element (ignoring any other nodes such as comments or elements), in tree order. On setting, it must act the same way as the textContent IDL attribute.

Since the <script> element is empty (you specified an external source), text, textContent and innerHTML are empty. This is because the text attribute is only set in inline scripts:

If the script is inline and the script block's type is a text-based language:

The value of the text IDL attribute at the time the element's "already started" flag was last set is the script source.

So it's not possible to include an external text/plain using this method.

See also:

  • W3C: HTML5: 4.11.1 The script element: text attribute and the example for the game map:

    <script src="game-engine.js"></script> <!-- game engine isn't inline -->
    <script type="text/x-game-map"> <!-- but data needs to be inline -->
    ........U.........e
    o............A....e
    .....A.....AAA....e
    .A..AAA...AAAAA...e
    </script>
    

这篇关于如何访问通过 &lt;script type="text/plain" 检索的纯文本内容src=...>在 JavaScript 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆