Possible Duplicate:
jquery - Read a text file?
I want to read a local text file, using jQuery. So I try this:
$.get('file_to_read.txt', function(data) { do_something_with(data) });
However, jQuery interprets "file_to_read.txt" as an html file and I get a Javascript error because it's not properly formatted and "do_something_with" does not have its desired effect, since data is not a string.
the jQuery doc says I need to specify the datatype. However, they only list html, xml, json and script as the possible data files; what should I do with a plain txt file I want to load directly into a string?
Use 'text'
datatype in your $.get()
request.
$.get('file_to_read.txt', function(data) { do_something_with(data) }, 'text'); // ^------last argument
Otherwise jQuery guesses at what was returned.
Remeber, $.get
is just a convenience wrapper for $.ajax
. The datatypes are listed in the $.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With