gpt4 book ai didi

javascript - 使用 jQuery 读取文本文件

转载 作者:行者123 更新时间:2023-12-03 21:47:26 26 4
gpt4 key购买 nike

Possible Duplicate:
jquery - Read a text file?

我想使用 jQuery 读取本地文本文件。所以我尝试这样做:

$.get('file_to_read.txt', function(data) {
do_something_with(data)
});

但是,jQuery 将“file_to_read.txt”解释为 html 文件,并且我收到 Javascript 错误,因为它的格式不正确,并且“do_something_with”没有达到预期的效果,因为数据不是字符串。

jQuery 文档说我需要指定数据类型。然而,他们只列出了 html、xml、json 和 script 作为可能的数据文件;我应该如何处理想要直接加载到字符串中的纯 txt 文件?

最佳答案

$.get() 请求中使用 'text' 数据类型。

$.get('file_to_read.txt', function(data) {
do_something_with(data)
}, 'text');
// ^------last argument

否则 jQuery 会猜测返回的内容。

<小时/>

请记住,$.get 只是 $.ajax 的便捷包装。数据类型列在 $.ajax() docs 中...

dataType

Default: Intelligent Guess (xml, json, script, or html)

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

"xml": Returns a XML document that can be processed via jQuery.

"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.

"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.

"text": A plain text string.

multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml." Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml.

关于javascript - 使用 jQuery 读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10112509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com