开发者

Loading text file from web, and parsing it with a script?

开发者 https://www.devze.com 2022-12-15 15:14 出处:网络
My .html has some associated data in a .txt file that I need to load when the page is loaded.I then need a script to be able to parse that data and do stuff with it in the page.Is there a quick-n-dirt

My .html has some associated data in a .txt file that I need to load when the page is loaded. I then need a script to be able to parse that data and do stuff with it in the page. Is there a quick-n-dirty way to do this? I was thinking I could just have a hidden and then run through its innerHTML, but DIVs don't seem to support that.

Thanks in advance...new to开发者_如何学Python web stuff!

EDIT: here's another catch: I want this to work, ideally, if the .html is loaded either from an actual website or from a local machine. To my knowledge, AJAX and XMLHttpRequest won't work in this situation(?)


Do you have flexibility in the format of the text file? If so I would store the data in the text file in JSON format and just include it in the HTML head of the page using script tags. Then you can use some JavaScript when the page is ready to parse the information stored in the text/JSON file and manipulate the HTML page as needed.

The nice thing about this approach is that it is simple and does not require server side code. You didn't mention whether or not the text file was dynamically generated but it doesn't matter with this approach.


You should use AJAX to load the text and a callback function to parse it according to your requirements and perform whatever actions are necessary. If you're using a framework like jQuery, look into the jQuery AJAX functions: http://docs.jquery.com/Ajax

If you're not using a framework and are instead coding straight JavaScript, look at using the XMLHttpRequest object: https://developer.mozilla.org/en/XmlHttpRequest


That should be done server side using a programming language like PHP or Perl or such. If you have to do it with JavaScript for some odd reason, the only way is to do AJAX call to the file and insert it into the DOM. There's plenty of tutorials for that.

And yes, innerHTML works on div elements, as well as with everything else.

0

精彩评论

暂无评论...
验证码 换一张
取 消