JavaScript

Moderators: None (Apply to moderate this forum)
Number of threads: 2061
Number of posts: 5164

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Possible to read from a file with JavaScript? Posted by hippychic43 on 2 Feb 2005 at 10:21 PM
This message was edited by hippychic43 at 2005-2-2 22:23:11

Hi,

I saw an earlier post asking if it was possible to read and write files with JavaScript and an answer stated that Active X was needed for writing, but what about if I only want to read a file? Is there anyway I can read a text file with Javascript to be able to analyse the contents of the text file?

I only want to be able to examine the files in my own website, nothing on the user's computer or anything.

Thanks
Cristy


Report
Re: Possible to read from a file with JavaScript? Posted by the walrus on 2 Feb 2005 at 11:16 PM
umm, you certainly can't read files on the user's computer (think of what a security risk that would be if a website could just read your files and email them off to whoever it wanted), but yes there are ways to read files from the server. the way you would go about doing that, and the complexity of the script, kind of depends on what kind of files you wanted to read and what you wanted to do with those files. there's not really a basic solution i could post that would work for general needs; could you give me more information about what you wanted to do?
Report
Re: Possible to read from a file with JavaScript? Posted by hippychic43 on 6 Feb 2005 at 7:56 PM
This message was edited by hippychic43 at 2005-2-6 20:7:53

Ok, the website I am creating isn't a website for the internet it is a website for a CD that is being used to present some content. I've created a Search Engine in Java Script that searches through a JS Array for keywords that the user searches for, and when it finds a match it brings up the details of the pages that are matches on another page. The problem is the JS Array only contains a few keywords that the pages contain. What I want to do is create an advanced search that actually traverses all of the HTML pages to see if a keyword that the user searches on actually exists in the whole documentation. So I only want to be able to open HTML files and read what's in them to see if it matches a keyword the user has entered as a search term.

I've noticed the mention of Active X controls before, is it necessary to develop an Active X control in Java to accomplish this? Or is there one already available I just have to use it?

Thanks


Report
Re: Possible to read from a file with JavaScript? Posted by the walrus on 6 Feb 2005 at 8:34 PM
here's a little example that might be able to do what you want. in this case it loads the text of the pages into a string, which could be used for processing, but the example just shows the value of the string in an alert box. there's probably a better way to do this, but this is what i came up with:

<html><head>
<script language="javascript" type="text/javascript"><!--

var xf = '', xPage = 0, Pages = new Array(2);

Pages[0] = 'test1.html';
Pages[1] = 'test2.html';
Pages[2] = 'test3.html';

window.onload = function() {xf = document.frames['FrameX'];};

function loadPage(PageRef) {

	xf.location.href = PageRef;
	setTimeout('getdoc()', 100);

}

function getdoc() {

	var DocText = xf.document.all[0].innerText;
	alert(DocText);

	if(xPage < Pages.length - 1) loadPage(Pages[++xPage]);

}

//--></script>
</head><body>
Click "Show Pages" to see page test1.html, test2.html, and test3.html in an alert box.
<input type="button" value="Show Pages" onClick="javascript:loadPage(Pages[0]);" />
<iframe id="FrameX" src="#" style="display: none" />
</body></html>


to see this example you'll need to save this in a .html file and also make files test1.html, test2.html, and test3.html and save them in the same folder. when you click the button, you should be displayed the contents of test1.html, test2.html, and test3.html. let me know if you have any more questions or problems.
Report
Re: Possible to read from a file with JavaScript? Posted by hippychic43 on 6 Feb 2005 at 8:47 PM
thanks heaps!

I didn't think it was possible with just Javascript, I think I should be able to adapt that perfectly to be able to do what I want.

Thanks
Cristy
Report
It only works in IE know another solution? Posted by hippychic43 on 7 Feb 2005 at 4:41 PM
Hi,

i've been testing out that code and such and have found that the document.all[0].innerText only works in IE, I need it to work across browsers, does anyone know of anyway to read a documents contents that exists in an iframe? or even the current frame? I've been looking through all of the methods and properties available and can't find anyway to return the text that is in the document, any help would be appreciated.

Thanks
Cristy
Report
fixed code that works in ie & firefox Posted by the walrus on 7 Feb 2005 at 5:23 PM
This message was edited by the walrus at 2005-2-7 17:25:55

<html><head>
<script language="javascript" type="text/javascript"><!--

var xf = '', xPage = 0, Pages = new Array(2);

Pages[0] = 'test1.html';
Pages[1] = 'test2.html';
Pages[2] = 'test3.html';

window.onload = function() {xf = frames['FrameX'];};

function loadPage(PageRef) {

	xf.location.href = PageRef;
	setTimeout('getdoc()', 100);

}

function getdoc() {

	var DocText = xf.document.all[0].innerHTML;
	alert(DocText);

	if(xPage < Pages.length - 1) loadPage(Pages[++xPage]);

}

//--></script>
</head><body>
Click "Show Pages" to see page test1.html, test2.html, and test3.html in an alert box.
<input type="button" value="Show Pages" onClick="javascript:loadPage(Pages[0]);" />
<iframe id="FrameX" name="FrameX" src="about:blank" style="display: none" />
</body></html>


the changes that were needed for it to work in firefox were:

1) give the iframe a name property so that firefox loads it correctly into the frames[] array

2) change src="#" to src="about:blank".. not necessary, but i noticed in firefox that the # cause the page to repeat over and over in the iframe, which would just waste memory, so about:blank would be a better way to do that

3) firefox doesn't seem to put the frames[] array in the document object, so get rid of the document.frames['FrameX'] part and just change it to frames['FrameX'].

4) change document.all[0].innerText to document.all[0].innerHTML. for some reason, it seems that firefox doesn't support innerText. unfortunately, using innerHTML means that you'll get all the tags along with the text, but for your purposes that probably wont really even matter. Note: if you only want to get the stuff inside the <body> tag you can do document.body.innerHTML instead.

these changes dont affect the script's ability to work in ie. i also tested in opera 7 and it worked fine with the changes.

hope this helps,
Nathan


Report
Re: fixed code that works in ie & firefox Posted by hippychic43 on 7 Feb 2005 at 8:37 PM
What do you use as a reference for JavaScript? Because the references I've been using don't list properties for document.body as in the innerHTML and innerText, it just lists the properties and methods for the first level of objects in the HTML DOM hierarchy, as in the document object, window, text etc.

I would love to get my hands on a reference that went even more indepth.

Thanks
Report
Re: fixed code that works in ie & firefox Posted by the walrus on 7 Feb 2005 at 9:08 PM
This message was edited by the walrus at 2005-2-7 21:11:28

: What do you use as a reference for JavaScript? Because the references I've been using don't list properties for document.body as in the innerHTML and innerText, it just lists the properties and methods for the first level of objects in the HTML DOM hierarchy, as in the document object, window, text etc.
:
: I would love to get my hands on a reference that went even more indepth.
:
: Thanks
:

well, honestly google is the best js reference anyone could ever ask for. usually you can kind of guess what the methods are going to be or type in a phrase that'll get you plenty of information. but to answer your question, msdn has a pretty good list of js objects, properties, and methods. http://msdn.microsoft.com/workshop/author/dhtml/reference/objects/body.asp

msdn isn't always the best at explaining things, but once you know the name of something you can google for it and find a lot more information, including how to get it to work in other browsers (msdn is obviously going to be specific to ie).
Report
Re: fixed code that works in ie & firefox Posted by Weirdofreak on 8 Feb 2005 at 11:47 AM
Personally, I use http://www.quirksmode.org for reference, but as the walrus said, Google is also very useful. I also wrote a script to recursively list the properties of an object, but just names, it isn't always easy to work out what you need, and not all browsers list everythig - IE, for instance, won't show methods.
^D
$ shameless-plug
http://line-ed.sourceforge.net

Report
Re: fixed code that works in ie & firefox Posted by kalliet on 11 Feb 2005 at 7:37 AM
Hello,

I haven't been writing much javascript code so far and I have been looking for this code for a few days now.
The example with the button works great, but I need to read that file when loading the page, so I can print a part of the content in the page.
I can't seem to invoke this.

If I remove the button and replace it by
<script language="javascript">
loadPage(Pages[0]);
</script>

--> then I get the error that xf.document is null

Suggestions?

thx,
kalliet
Report
Re: fixed code that works in ie & firefox Posted by the walrus on 11 Feb 2005 at 10:01 AM
the reason you get the error is because of two reasons. 1) xf doesn't reference the "FrameX" iframe yet. 2) the "FrameX" iframe probably doesn't exist on the page yet, because it loads after the script.

you'll notice that in the code theres a line that says

window.onload = function() {xf = frames['FrameX'];};


this tells the window to do something when it loads. an easy fix for whatyou want to do is to change that line to

window.onload = function() {
     xf = frames['FrameX'];
     loadPage(Pages[0]);
};


the problem with doing it this way is if you have a lot of pictures on the page it could take a while for the whole page to load (window.onload usually waits for all the pictures to load too, not just the html of the page ). to fix this you can add a script at the bottom of the page (right above the </html> tag) that says:

<script type="text/javascript"><!--
xf = frames['FrameX'];
loadPage(Pages[0]);
//--></script>


and delete that window.onload line.
Report
Re: fixed code that works in ie & firefox Posted by amosngweien on 19 Dec 2009 at 7:30 PM
Mine Is, NO Array NO Frames
1st: From A Page, Load Page Only

Add this code to your head tag
<script type="text/javascript">

//To include a page, invoke ajaxinclude("afile.htm") in the BODY of page
//Included file MUST be from the same domain as the page displaying it.

var rootdomain="http://"+window.location.hostname

function ajaxinclude(url) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.open('GET', url, false) //get page synchronously 
page_request.send(null)
writecontent(page_request)
}

function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || page_request.status==200)
document.write(page_request.responseText)
}

</script>


Once Thats Done, Add This Peace Of Code Where You Want It To Load
<script type="text/javascript">
ajaxinclude("afile.htm")
</script>

if you want it to load like http://programmersheaven.com,
Put This Code
<script type="text/javascript">
ajaxinclude(rootdomain+"/includes/afile.htm")
</script>

rootdomain+ Means, it will load your domain name
If You Want It To Be, Went somebody clicked this and will load
OnClick="ajaxinclude("afile.htm")
2nd: From A Page, Load The Page Text Only
Put This Bunch Of Code To Your Head Tag
<script type="text/javascript">


var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} 
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" " //Remember this object as being already added to page
}
}
}

</script>

Once Thats Done, Either Choose A Code:
Normal link:
<a href="javascript:ajaxpage('test.htm', 'contentarea');">test</a>
<div id="contentarea"></div>

Or , Normally load this code
<script type="text/javascript">
ajaxpage('test.htm', 'rightcolumn') //load "test.htm" into "rightcolumn" DIV
</script>

Load absolute URL link:
<a href="javascript:ajaxpage(rootdomain+'/mydir/index.htm', 'contentarea');">test</a>
<div id="contentarea"></div>

Using a drop down menu to load the links:
<script type="text/javascript">
/***Combo Menu Load Ajax snippet**/
function ajaxcombo(selectobjID, loadarea){
var selectobj=document.getElementById? document.getElementById(selectobjID) : ""
if (selectobj!="" && selectobj.options[selectobj.selectedIndex].value!="")
ajaxpage(selectobj.options[selectobj.selectedIndex].value, loadarea)
}
</script>

<form>
<select id="ajaxmenu" size="1">
<option value="page1.htm">Page 1</option>
<option value="page2.htm">Page 2</option>
<option value="subdirectory/page3.htm">Page 3</option>
</select>
<input type="button" onClick="ajaxcombo('ajaxmenu', 'contentarea')" value="Go" />
</form>


If you need the drop down menu to load absolute URLs on your site, just modify the "ajaxpage()" function in the above code to:
ajaxpage(rootdomain+"/"+selectobj.options[selectobj.selectedIndex].value, loadarea)

Finally, and if that wasn't enough, if you wish the drop down menu to load a file simply by selecting it from the menu (versus clicking on the "Go" button, change the entire form above to:
<form>
<select id="ajaxmenu" size="1" onChange="ajaxcombo('ajaxmenu', 'contentarea')">
<option value="">Select A file to load</option>
<option value="page1.htm">Page 1</option>
<option value="page2.htm">Page 2</option>
<option value="subdirectory/page3.htm">Page 3</option>
</select>
</form>

Load page and external CSS /JavaScript link:
<a href="javascript:ajaxpage('test.htm', 'contentarea'); loadobjs('external.css', 'feature.js')">test</a>
<div id="contentarea"></div>

Syntax of loadobjs():
Note that function loadobjs() can invoke any number of CSS and external JavaScript files that you need. For example:
loadobjs('external.css') //load one CSS file
loadobjs('external.css', 'external2.css', 'feature.js') //load 2 CSS files & 1 JS file
loadobjs('feature.js', 'feature2.js', 'feature3.js') //load 3 JS files




 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.