Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - Read a text file?

I have an html file that I'd like to open and read from, but I'm not entirely sure how to do that... Basically, it's a fairly large file (big.html), and, in a separate file (titles.html), I have some jquery code that I'd like to use to find certain elements (namely, h2 tags) and get the inner text from those tags and write just that text to titles.html... I'm not sure, particularly, how to open a separate file and read from it, and secondly, I'm not sure if the code below will work when it comes to getting the text within the h2 tags...

$(document).ready(function() {
    $("h2").each(function() {
        var title = $(this).text();
        $("#mydiv").append(title);
    });
});

...

<div id="mydiv"></div>

I'm a bit confused how to do that with jquery... I'm pretty new to the whole thing, so I'm not even sure it's possible...

like image 774
phpN00b Avatar asked Dec 30 '09 18:12

phpN00b


People also ask

How to read a text file using jQuery?

get() Read Text File Example. JQuery code snippet to read a text file via the built in AJAX jQuery. get() call and then process the txt file line by line. The example adds the lines to a html element for display on page.

How jQuery read data from JSON file?

To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery. getJSON( ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server.


1 Answers

jQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.

Untested, but the general gist of it...

var HTML_FILE_URL = '/whatever/html/file.html';

$(document).ready(function() {
    $.get(HTML_FILE_URL, function(data) {
        var fileDom = $(data);
        fileDom.find('h2').each(function() {
            alert($(this).text());
        });
    });
});
like image 141
T. Stone Avatar answered Sep 28 '22 20:09

T. Stone