Looking for advise on whether is it possible to have a footer.html and duplicate it to all pages without using PHP.
I know I can use include("footer.php"), but all my pages are in HTML now and I will have to change all css paths.
I read up w3school on how to use w3-include-html & javascript. However I realize the javascript is lagging every pages, making page loading longer.
Is there any other option?
<body>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
</script>
<div w3-include-html="footer.html"></div>
<script>
includeHTML();
</script>
You could think different, but I don't know if it is, what you want, because the architecture of your application will grow up / become a littlebit ugly.
You define a php-script, that is loading your static html and appends the php-code you want. Then you need a rewrite rule, to get the script as the center of your tiny html-universe ;-)
An example, that should work on an apache with rewrite-mod enabled.
Mention, that you create this directory-structure on your server:
.../.htaccess
.../index.php <<< this renders the "header", content of your html-files and last footer
.../html-pages <<< place your files here
Place an .htaccess in the root-folder:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond "%{REQUEST_URI}" !^.*/index\.php$
RewriteRule ^(?!.*index\.php)(.*)$ /index.php/$1 [QSA,L]
Place an index.php in the samefolder:
<?php
... here could be your header-code
define ('PAGES_DIR', __DIR__ . '/html-pages')
define ('DEFAULT_PAGE', 'index.html')
// we need to handle virtual pathes
$requestPath = false;
if (isset($_SERVER['PATH_INFO'])) {
$requestPath = $_SERVER['PATH_INFO'];
} elseif (isset($_SERVER['ORIG_PATH_INFO']) && strpos($_SERVER['ORIG_PATH_INFO'], basename(__FILE__)) === FALSE) {
$requestPath = $_SERVER['ORIG_PATH_INFO'];
}
if ($requestPath == '/' || strlen(trim($requestPath)) == 0 || strlen(trim($requestPath)) == basename(__FILE__)) {
$requestPath = DEFAULT_PAGE;
}
// this sends the content of your file to the browser
#readfile(PAGES_DIR . "/$requestPath");
... now your footer-code
And your html-files needs be placed into the "html-pages"-folder.
If you have done, your server should handle http://domain.tld/bla-fasel-blub.html as followed:
redirect the not existing path to index.php
RewriteRule ^(?!.index.php)(.)$ /index.php/$1 [QSA,L]
render the header
read the requested html-file (the $1 of the RewriteRule will be "bla-fasel-blub.html" and becomes value of "$requestPath") and send the content to the browser
render the rest of index.php (the footer or whatever)
I hope it helps, generating an idea for your problem.
Related
So this is our scenario... First thing we do is, we append a piece of javascript code which adds external script to document like this:
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = 'http://blabla.com/script.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
})();
Then in script.js following happens:
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
createDiv(xmlhttp.responseText);
}
};
xmlhttp.open("GET","http://blabla.com/api/");
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext)
{
var dom = parseResponse(responsetext);
var _ws = dom.getElementById('styles');
var h = document.getElementsByTagName('head')[0];
h.appendChild(document.importNode(_ws, true));
var _jr = dom.getElementById('script1').outerHTML;
var _vc = dom.getElementById('script2').outerHTML;
var _rv = dom.getElementById('script3').outerHTML;
var _rw = dom.getElementById('my_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'just_id';
_d.innerHTML = _jr + _vc + _rv;
_d.appendChild(document.importNode(_rw, true));
_b.appendChild(_d);
}
ajaxCall();
Everything works fine, script's and a div are being appended as expected and where expected, but appended script doesn't get executed and doesn't affect appended div. Why is that? And how can I make it execute? We also don't get any warnings/errors in console. Using latest firefox.
EDIT 1
Comment: The example script you showed just defines function, but it never actually calls them
It actually calls a function which makes an ajax request, please check edited code snippet.
EDIT 2
Comment: Have you tried to put the logic in a callback and then call it in createDiv? May be add some logs to test if its getting called but it unable to find div
I just tried console.log('hello world'); call in one of scripts which are being appended by createDiv() function, but it does nothing.
EDIT 3
For more details. When page is loaded, I can see
<script type="text/javascript" id="script1" src="http://blabla.com/script1.js"></script>
<script type="text/javascript" id="script2" src="http://blabla.com/script2.js"></script>
<script type="text/javascript" id="script3" src="http://blabla.com/script3.js"></script>
<div id="just_id">Content here</div>
In DOM-Inspector and as mentioned above, there is console.log('hello world'); to test it, but it doesnt get executed.
EDIT 4
Added some CSS through createDiv() function to document's <head></head> and it affects my div with id 'just_id'. JS still isn't working.
EDIT 5
Also tried to append inline javascript instead of external one in my function, but still no success. Can see following in DOM-Inspector, but code doesn't log anything.
<script type="text/javascript">
console.log('test');
</script>
EDIT 6
I also tried to import nodes from as suggested here
This method is not allowed to move nodes between different documents. If you want to append node from a different document the document.importNode() method must be used.
and also tried to changed order. 1.css 2.div 3.js like this but still no success... Anyone has an idea what is going on here?
Check the code above
EDIT 7
As suggested in How do you execute a dynamically loaded JavaScript block? I set innerHTML of my div to scripts + content and then appended to DOM like this:
Check the code above
But still without any success.
EDIT 8
Added ajax function code. 3rd paramter in xmlhttp.open("GET","http://blabla.com/api/"); true (asynchronous) and false (synchronous) already tried. Still no success.
EDIT 9
function createDiv() as suggested in answer:
var dom = parseResponse(responsetext);
var _jr = dom.getElementById('script1'); //<script> tag with src attribute
var _vc = dom.getElementById('script2'); //inline <script> for test purposes only, it should actualy be external script also
var _rv = dom.getElementById('script3'); //inline <script>
var _rw = dom.getElementById('external_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'internal_div';
_d.appendChild(document.importNode(_rw, true));
_d.appendChild(document.importNode(_jr, true));
_d.appendChild(document.importNode(_rv, true)); //without second parameter TRUE, I dont get script content
_d.appendChild(document.importNode(_vc, true)); //without second parameter TRUE, I dont get script content
_b.appendChild(_d);
Doesn't work. Work's only if I take innerHTML of inline scripts from other document, create elements like suggested in answer, set their innerHTML and then append do current document. External script's wont load at all.
EDIT 10
.htaccess from localhost... :
<Files *.html>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
<Files index.php>
Order Allow,Deny
Allow from all
</Files>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /page1/
#RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
.htaccess from 192.*** ... :
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /direktexpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /page2/index.php [L]
</IfModule>
# END WordPress
EDIT 11
So I am probably going to give bounty #Drakes, just for the effort and his spent time on my question and going to show some screenshots what is going on. It is definitely firefox bug, I just tested on chrome and it works.
1st picture: source code of 192.168.2.197/testing/whatever/etc. .htaccess remains the same as in example above
2nd picture is source code for script.js, which is being loaded on 192.168.2.197/testing/whatever/etc. .htaccess remains the same as in example above:
3rd picture is a screenshot of inspector, how does my dom look like:
4th picture.... nothing happens. Just a warning which has nothing to do with my problem (I hope so), because even when I remove all scripts, it still appears.
Is it a firefox bug?
The problem is that the code above is mixing appendChild with innerHTML. It's not intuitively obvious that the two perform differently in some cases. The former allows newly inserted script nodes to be executed as they are attached to the DOM. The latter doesn't. This has been a head-scratcher for many people. Kindly Google "script and innerHTML" and you will find that you are not alone facing this similar problem.
If you (1) change
_d.innerHTML = _jr + _vc + _rv
to
_d.appendChild(document.importNode(_jr));
_d.appendChild(document.importNode(_vc));
_d.appendChild(document.importNode(_rv));
and additionally (2) change
var _jr = dom.getElementById('script1').outerHTML;
var _vc = dom.getElementById('script2').outerHTML;
var _rv = dom.getElementById('script3').outerHTML;
to
var _jr = dom.getElementById('script1');
var _vc = dom.getElementById('script2');
var _rv = dom.getElementById('script3');
then your scripts will get executed. Here is a demonstration:
var b = document.getElementsByTagName('body')[0];
/* Works */
var s1 = document.createElement('script');
s1.innerHTML = "console.log('I will execute')";
b.appendChild(s1);
/* Fails */
var s2 = document.createElement('script');
s2.innerHTML = "while(1){alert('Do not worry! I will not execute');}";
b.innerHTML = s2.outerHTML;
console.log("It didn't execute");
Tested
I ran the OP's code on my server to replicate the problem as best I can. Given the supplied code I can make it work as intended on my server. I only changed the AJAX URL from http://blabla.com/api/ to api.html and supplied my own file as none was provided by the OP, but I pieced together what it should contain from the OP's JavaScript). Here are sample results:
index.html
<html lang="en">
<body>
<script>
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = 'script.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
})();
</script>
</body>
</html>
script.js
This is the OP's code modified to my specifications above (using appendChild instead of innerHTML, and the AJAX call returns the contents of api.html below)
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
createDiv(xmlhttp.responseText);
}
};
xmlhttp.open("GET","api.html");
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext)
{
var dom = parseResponse(responsetext);
var _ws = dom.getElementById('styles');
var h = document.getElementsByTagName('head')[0];
h.appendChild(document.importNode(_ws, true));
var _jr = dom.getElementById('script1');
var _vc = dom.getElementById('script2');
var _rv = dom.getElementById('script3');
var _rw = dom.getElementById('my_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'just_id';
_d.appendChild(document.importNode(_jr, true));
_d.appendChild(document.importNode(_vc, true));
_d.appendChild(document.importNode(_rv, true));
_d.appendChild(document.importNode(_rw, true));
_b.appendChild(_d);
}
ajaxCall();
api.html (returned by the AJAX call)
<!DOCTYPE html>
<html>
<body>
<style type="text/css" id="styles"></style>
<script type="text/javascript" id="script1" src="script1.js"></script>
<script type="text/javascript" id="script2">console.log("incline script 2")</script>
<script type="text/javascript" id="script3">console.log("incline script 3")</script>
<div id="my_div"></div>
</body>
</html>
script1.js
console.log("src script1");
Here are the DevTools results to show this is working.
The JavaScript of the page has already been parsed, you need to eval the result to put it into the window context.
function evalRequest(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
};
UPDATE : you might need to get the script as text and then eval it )
function getScriptsAsText() {
var div = document.createElement('div');
var scripts = [];
var scriptNodes = document.getElementsByTagName('script');
for (var i = 0, iLen = scriptNodes.length; i < iLen; i++) {
div.appendChild(scriptNodes[i].cloneNode(true));
scripts.push(div.innerHTML);
div.removeChild(div.firstChild);
}
return scripts;
};
The problem is your method is asynchronous not synchronous execution. Meaning the page is still loading while you insert your dynamical scripts.
There are few ways to do so:
The easiest way is to use jQuery $(document).append instead of
document.createElement, if you don't mind using the library.
You can also use jQuery $.getScript.
If you prefer not to include 3rd libraries, you have to think of a way to delay page load while you insert your scripts, something like an alert to creat a prompt window will work, but user experience not so good, think of a more smooth way.
Use XMLHTTPRequest to retrieve your scripts. This is synchronous and I can see you are familiar with it because you are using it in your script already.
Good luck and happy coding.
Have you tried getting the URL of the src file and excuting it with jQuery's getScript() function?
Change your creatediv() function :
var _jr = dom.getElementById('script1').outerHTML;
var srcScript1Left = _jr.split('src="');
srcScript1Right = srcScript1Left[1].split('"');
srcScript1 = srcScript1Right[0];
console.log(srcScript1);
$.getScript(srcScript1, function()
{
// The external script has been executed.
});
EDIT
Similar method in pure Javascript :
var _jr = dom.getElementById('script1').outerHTML;
var srcScript1Left = _jr.split('src="');
srcScript1Right = srcScript1Left[1].split('"');
srcScript1 = srcScript1Right[0];
console.log(srcScript1); // Display the name of the external script file
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText); // Execute the external script
}
};
xmlhttp.open("GET",srcScript1);
xmlhttp.send();
You are currently loading a script into your page. This happens AFTER the page js was already executed (since is async and usually loading an external resource takes longer than the script execution).
So... basically you have the right function definitions and everything, and calling them from console later should work (I think you already tried that and was fine).
Still, the calls to your functions, even thought they are there won't execute since will not be computed after load.
To work around this, you can create an ajax request to a page that has the script, and in its callback to call whatever function you need to call.
I would say remove async, as the action comes after the initial page load
(function () {
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(CreateScriptTag('http://blabla.com/script.js',true), s);
})();
function CreateScriptTag(src, isAsync) {
var e = document.createElement('script')
e.type = 'text/javascript';
e.async = isAsync;
e.src = src;
return e;
}
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://blabla.com/api/");
xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) createDiv(xmlhttp.responseText); };
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext) {
var head=document.getElementsByTagName('head')[0],dom = parseResponse(responsetext),_div=document.createElement('div');
head.appendChild(document.importNode(dom.getElementById('styles'), true)); //Assuming stylesheets are working fine.
_div.id = 'just_id';
//div.innerHTML = _script1 + _script2 + _script3;
document.getElementsByTagName('body')[0].appendChild(_div.appendChild(dom.getElementById('my_div')));
head.appendChild(CreateScriptTag(dom.getElementById('script1').getAttribute("src"),true));
head.appendChild(CreateScriptTag(dom.getElementById('script2').getAttribute("src"),true));
head.appendChild(CreateScriptTag(dom.getElementById('script3').getAttribute("src"),true));
/* or another idea;
document.write(_script1 + _script2 + _script3);
*/
}
ajaxCall();
I have a type of SPA which consumes an API in order to fetch data. There are some instance of this SPA and all of them use common style and script files. So my problem is when I change a single line in those files, I will have to open each and every instances and update the files. It's really time consuming for me.
One of the approaches is to put those files in a folder in the server, then change the version based on the time, but I will lose browser cache if I use this solution:
<link href="myserver.co/static/main.css?ver=1892471298" rel="stylesheet" />
<script src="myserver.co/static/script.js?ver=1892471298"></script>
The ver value is produced based on time and I cannot use browser cache. I need a solution to update these files from the API, then all of the SPAs will be updated.
In your head tag, you can add the code below:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:4000/getLatestVersion"; //api path to get the latest version
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var tags = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < tags.length; i++) {
var tag = document.createElement(tags[i].tag);
if (tags[i].tag === 'link') {
tag.rel = tags[i].rel;
tag.href = tags[i].url;
} else {
tag.src = tags[i].url;
}
document.head.appendChild(tag);
}
}
};
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
</script>
Your api path should allow "CORS" from your website that handles the code above.
And your api should return a json data like below:
var latestVersion = '1892471298'; //this can be stored in the database
var jsonData = [
{
tag: 'link',
rel: 'stylesheet',
url: 'http://myserver.co/static/main.css?ver=' + latestVersion
},
{
tag: 'script',
rel: '',
url: 'http://myserver.co/static/script.js?ver=' + latestVersion
}
];
//return jsonData to the client here
If you change anything in your JS or CSS then you have to update the browser cache, all you can do is to update that particular JS version not all of them, it should reflect in browser.
How about adding a method in your API returning the files' last modified time and then inserting the value into the "src"/"href" attribute after the "ver="
I am using caledar.js file by adding it to html code.
Till server migration, it was working perfectly. But now Instead of showing calendar, calendar.js code is shown...
My code to add calendar.js is as follows :
<div id="Calendar" src="calendar.php"> </div>
<div id="Events" src="events.php"> </div>
<script language="javascript" TYPE="text/javascript" src="calendar.js"></script>
Now instead of showing calendar, calendar.js code is shown on webpage as follows (eg):
var bustcachevar=1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var bustcacheparameter="";
function createRequestObject(){
try {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
};
return xmlhttp;
};
function ajaxpage(url, containerid){
var page_request = createRequestObject();
if (bustcachevar) bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
}
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 LoadMonth(month, year) {
ajaxpage("calendar.php?month="+month+"&year="+year, "Calendar")
}
function LoadEvents(date) {
ajaxpage("events.php?date="+date, "Events")
}
LoadMonth();
I also tried adding following code in css file
script{
display:none;
}
head{
display:none;
}
Is there any need to change in above calendar.js code as server is migrated from php5.3 to php5.4 ?
Here I Got Solution. I am posting it as an answer so others may get answer if they are facing same issue...
I added following code in my root .htaccess file and now it works....
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
I'm trying to use jQuery to read all text files in a folder and display their contents, but then, filter which should ones should be displayed based on the name of the folder.
Here's the JavaScript:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt": "",
"01600610/9874565214_789545623.txt": ""
};
$.each( obj, function(SavedText) {
$.get(SavedText, function(data){
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ data +'</div>')
}, 'text');
});
On this:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt":"",
"01600610/9874565214_789545623.txt":""
};
Q1: How do I get all text files inside a folder instead of specifying the file I want?
Q2: How can I filter? For example, how can I only get files ending or starting with 789545.
When these files are on your local filesystem, you can use the HTML5 Filesystem API.
If the files are located on a server, there is no way listing them from plain (client-side) javascript (maybe except a brute-force method, which shouldn't be considered of course). Then you have to write a server script (in PHP/Node/Perl/Phython/...) which will respond to a ajax request with a file list.
If you are using a server script, you should do the filtering on the server (so the answer depends on the language).
Otherwise you should use Regular Expressions:
var search = new RegExp("789545");
for(var file in obj) {
if(search.test(file))
alert(file+": "+obj[file]);
}
This would search for files with a name containing the pattern 789545
Please create index.php file and add this content to it. Create there a folder called "files" and add your files there
<?php
function contains($haystack, $needle){
if (strpos($haystack,$needle) !== false) {
return true;
}
return false;
}
if(isset($_POST['get_files'])){
$folder = "";
$filter = "";
if(isset($_POST['folder'])){
$folder = $_POST['folder'];
}
if(isset($_POST['filter'])){
$filter = $_POST['filter'];
}
$files = array();
foreach(glob($folder.'/*.*') as $filename){
if($filter != ""){
if(contains($filename, $filter)){
$files[] = $filename;
}
}else{
$files[] = $filename;
}
}
print_r($files);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getData(){
jQuery.post('index.php',{
get_files:true,
folder:"files",
filter:""
},function(data){
jQuery('#container').html(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get data" onclick="getData();" />
<div id="container"></div>
</body>
</html>
You can specify different folder, and filename filter in jQuery post request call
U can use regular expressions to filter the filenames. And for getting all files in a folder, U want to run a server side script. I use perl or php, to do this kinda stuff. U can use ajax to post the request and make the server script to return the file contents.
http://perlmeme.org/faqs/file_io/directory_listing.html
This link is just an example to do what u need in perl. And u could possibly do the same with other languages too
I'd like to load/insert an external html page into my web page. Example :
<b>Hello this is my webpage</b>
You can see here an interresting information :
XXXX
Hope you enjoyed
the XXXX should be replaced by a small script (the smaller as possible) that load a page like http://www.mySite.com/myPageToInsert.html
I found the following code with jquery :
<script>$("#testLoad").load("http://www.mySite.com/myPageToInsert.html");</script>
<div id="testLoad"></div>
I would like the same without using an external javascript library as jquery...
There are 2 solutions for this (2 that I know at least):
Iframe -> this one is not so recommended
Send an ajax request to the desired page.
Here is a small script:
<script type="text/javascript">
function createRequestObject() {
var obj;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(req) {
var http = createRequestObject();
http.open('get', req);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
document.getElementById('setADivWithAnIDWhereYouWantIt').innerHTML=response;
}
}
sendReq('yourpage');
//previously </script> was not visible
</script>
Would an iframe fit the bill?
<b>Hello this is my webpage</b>
You can see here an interresting information :
<iframe id="extFrame" src="http://www.mySite.com/myPageToInsert.html"></iframe>
Hope you enjoyed
You can set the src attribute of your iframe element using plain old javascript to switch out the page for another
I think what you are looking for are in the Jquery source code.
you can see more details here $(document).ready equivalent without jQuery