I am creating a simple web application for a comic using HTML and JavaScript. Because people that are not very technical should be able to add new comics, I thought about using an XML file as a configuration file.
I thought about using JSON and decided against it, mainly because the way comma's are used(no comma between two items breaks it, but a comma at the end of the list also breaks it.).
However, my question is now: How can I embed this XML file? Do I use the <link rel= /> tag, or something else like the <embed src= /> tag? And how can I then read information from the XML nodes in JavaScript?
I would recommend loading a JavaScript library that makes this easy. jQuery is one. If you include jQuery in your page then you use it to load the document and get access to the browser's XML parsing capabilities fairly easily.
http://api.jquery.com/jQuery.parseXML/ shows a simple example of finding values in an xml document once it's loaded.
This site http://think2loud.com/224-reading-xml-with-jquery/ gives a good example of how to load XML from a remote site. The basic idea is to use AJAX: here's a tiny snippet for posterity that will load foo.xml after the html document has loaded (relies on jQuery):
$( function() {
$.ajax({
type: "GET",
url: "foo.xml",
dataType: "xml",
success: myHandler(xml) {
}
});
});
Use xml tag. Example :
<html>
<xml Id = msg>
<message>
<to> Visitors </to>
<from> Author </from>
<Subject> XML Code Islands </Subject>
</message>
</xml>
</html>
Related
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
I'm writing a static web site that uses JQuery to make some AJAX calls to a RESTful API and populate the page with data.
The site functions correctly (and quickly), everything is good.
As I extend the site and add additional pages, I'm noticing that I'm duplicating certain regions on every page.
For instance, each page shares a common header element.
<header>...Some non-trivial content...</header>
Rather than repeat this definition on each page is there some mechanism, by which, I can define this section once and include it in each document.
Remember that the pages must be served statically but any standard complaint browser functionality can be utilised.
Is there a good way to do this, and what is it or, will I have to abandon DRY principles for this aspect of my client side code?
There's definitely some ways to achieve this. You could either do it using some features of your server-side language that allows to include the content of a page in another page, or if you do not have any server-side technology, you could simply put that code in it's own html document and load it's content using AJAX.
In jQuery it could look like:
$('#header').load('header.html');
However, if the content isin't static for all pages, you could always define a JS module that would be responsible to render this header. You module could make use of a client-side templating engine, like Mustache, Handlebars, etc. However you do not have to use any of these.
Here's a simple example:
DEMO
//in somefile.js, please note that you should namespace your modules
var Header = {
//default config
config: {
el: '#header',
title: 'Some title'
},
init: function (config) {
var cfg = this.config = $.extend({}, this.config, config);
$(cfg.el).html('<h1>' + cfg.title + '</h1>');
}
};
$(function () {
Object.create(Header).init({
title: 'Some other title'
});
Object.create(Header).init({
el: '#header1',
title: 'Yeah'
});
});
As I mentioned in the comment, this is how I do it:
main.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Main page</title>
<sript src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$('#commonsection').load('reusablefile.htm');
// which is eqvivalent to:
//
// $.ajax({
// url: 'reusablefile.htm',
// dataType: 'html',
// success: function(data){
// $('#commonsection').html(data);
// }
// });
});
</script>
</head>
<body>
<div id="commonsection"></div>
</body>
</html>
reusablefile.html:
<script>
(function($){ //separate scope to keep everything "private" for each module
//do additional javascript if required
})(jQuery);
</script>
<p>...Some non-trivial content...</p>
You could use jQuery's ajax as to load the header file. In each file you could load the html like so:
$('#header').load('header.html');
Since you're already using AJAX calls to populate your site with data, you could do the same for the common regions.
Just store the HTML for those regions in a separate file and load it in the page with AJAX. Also, you can work with caching using the Cache-Control headers on that file so you don't reload the entire content from the server with each page load.
If you're using straight HTML, you could do it with a SSI include command or by creating a template page and including it in jQuery. Both of these links might help you
Include another HTML file in a HTML file
and
http://www.htmlgoodies.com/beyond/webmaster/article.php/3473341/SSI-The-Include-Command.htm
It looks like this in modest:
main.xhtml
<?xml version='1.0' encoding='UTF-8'?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<include>reusablePiece</include>
</head>
<body>
<reusablePiece/>
</body>
</html>
reusablePiece.xml
<header>...Some non-trivial content...</header>
Very simple would be the jQuery .clone() function.
If you have more complex content I recommend looking at Handlebars.js which is a full fledged JS templating engine.
UPDATE 1
Here is how I am currently loading text into my WT project.
wApp->require("ace.js");
//orignal XML, reads in incorrectly on one line
//std::string data = ReadFile("Q:\\settings.xml");
//XML after being formatted in notepad to look like xml, reads in correctly
//std::string data = ReadFile("Q:\\settings.txt");
//changed extension back to XML, edited in notepad++ to XML format, reads in correctly
std::string data = ReadFile("Q:\\settings_from_text.xml");
//test xml tag, reads in correctly
//std::string data = "<tag_1>some tag content</tag_1>";
//test xml tag with newline, reads in incorrectly on one line, doesnt read newline
//std::string data = "<tag_1>some tag content</tag_1>\n<tag_1>some tag content</tag_1>";
_ace_editor = new WText(data, Wt::PlainText);
//_ace_editor->setText(data);
_ace_editor->setInline(false);
// A WContainerWidget is rendered as a div
_ace_editor->resize(1000, 500);
std::string editor_ref = _ace_editor->jsRef(); // is a text string that will be the element when executed in JS
std::string command =
editor_ref + "._ace_editor = ace.edit(" + editor_ref + ");" +
editor_ref + "._ace_editor.setTheme(\"ace/theme/chrome\");" +
editor_ref + "._ace_editor.getSession().setMode(\"ace/mode/xml\");";// +
//editor_ref + "._ace_editor.setValue(\"" + data + "\");";
_ace_editor->doJavaScript(command);
Also, here is the ReadFile function
std::ifstream in(path, std::ios::in | std::ios::binary);
if(in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
throw(errno);
ORIGINAL POST
I am trying to load some XML files into an Ace (http://ajaxorg.github.io/ace/#nav=about) editor that I embedded in a WT (http://www.webtoolkit.eu/wt?wtd=rqBfShGlNupXgK3M1sWOxUk1Loz3BsW0) page. The problem is that XML files for whatever reason have all their tags omitted from the load. Example: An XML file with the following content
<?xml version="1.0"?>
<settings>
<tag_1>some tag content</tag_1>
<tag_2/>
</settings>
will be loaded as
some tag content
I need the entire XML file as is, not just the contents of the tags.
After doing a bit of research, I have found quite a few other people on different forums asking the same thing but everything I have tried so far has not been working, which brings me here.
This includes setting the Ace mode to XML, trying to load the text in a different container before setting it to the ace window, changing the color schemes, and parsing a file in a different manner.
I am using visual studio 2010, and from debugging I can see that the file does get read in fully into a string with all the tags, but after it is set to the Ace window they are omitted.
Regardless of whether you are putting it on a WT page or not, bottom line this is a javascript question as that is what the ACE editor is, a javascript tool. Since you have not shown anything at all about how you are loading the xml content, I can only speculate that you must be writing the contents of the xml file into the pages output source?? I'll bet if you view-source do you see the tags? Well if so you are going about it wrong. The xml file needs to be loaded via javascript/ajax as I will demonstrate with a fully working example below (edit the 'url' in the $.ajax call to location of an xml file on your server), which shows tags and all contents of the xml file. Added the jQuery library just for simplicity of the ajax request code. Enjoy!
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#editor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
</style>
</head>
<body>
<div id="editor"></div>
<script src="http://rawgithub.com/ajaxorg/ace-builds/master/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
var callback = function (data, status, xhr) {
//data will be the xml returned from the server
if (status == 'success') {
var editor = ace.edit("editor");
//apparently, only modes supported are 'html', 'javascript' & 'text'
editor.getSession().setMode("ace/mode/html");
editor.setValue(data);
}
};
//using jQuery to fire off an ajax request to load the xml,
//using our callback as the success function
$.ajax(
{
url : '/testing/cd_catalog.xml',
dataType : 'text', //explicitly requesting the xml as text, rather than an xml document
success : callback
}
);
</script>
</body>
</html>
Actually, I take back some of what I said about the "must load via javascript/ajax", as I now realize you were just following ACE's example of putting the contents into the editor div beforehand. If you want to do that with html or xml content, the tags will be evaluated by the browser and not show up, unless you copy the editor div's innerHTML then instantiate the editor and then set it's value to the previously saved innerHTML. For example:
<div id="editor"><?xml version="1.0" encoding="ISO-8859-1">
<books>
<text>some text content</text>
<book/>
</books></div>
<script src="http://rawgithub.com/ajaxorg/ace-builds/master/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
var txt = document.getElementById('editor').innerHTML;
var editor = ace.edit("editor");
//editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/html");
editor.setValue(txt);
</script>
XML fragments in XML... you can somehow expect that your browser will interpret them, unless properly escaped. Try this:
txt = new WText("<bla>something</bla>", Wt::PlainText);
which will escape all XML-ish characters in your text.
Wt's default (XHTMLText) will try to parse your input as XML, and if it succeeds filter possible XSS vectors from the XML before sending it as XML to the browser. If it can't parse the text as XML, it will escape XML-ish characters to avoid that a browser with a liberal parser would unintentionally execute attack vectors.
The third option (XHTMLUnsafeText) bypasses XSS filtering - dangerous, so only use it when you know that your text is safe and can not be influenced directly or indirectly by the user.
I want javascript to load a html code so it can be embedded in a page, all I get is the raw html code without being compiled.
<script>
document.write('http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html')
</script>
It contains the html coding inside and I want it to embed in pages so I can share with other websites.
Are you trying to get the HTML from that URL and embed it in the page? JavaScript can't do that for security reasons, but if you're using PHP server-side you can use:
echo file_get_contents("http://..........");
Or you can use an iframe:
<iframe src="http://........" />
The easiest way to make this work, sort of, is by using <iframe>:
<iframe src="http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html"></iframe>
If you want to load it inside a particular container, you have to perform a web request using JavaScript; jQuery example:
<div id="container"></div>
<script>
$('#container').load('http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html');
</script>
If the remote URL is not in the same domain, you need to use a proxy:
<script>
$('#container').load('/path/to/myproxy.php', {
url: 'http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html'
});
</script>
Then your PHP code could look like:
<?php
if (parse_url($_POST['url'], PHP_URL_HOST) === 'www.example.com') {
echo file_get_contents($_POST['url']);
}
document.write - adds text to the document - it does not fetch documents from the web.
However, you can use the object tag.
It should look something like that:
<object type="text/html" data="http://www.example.com/index.php?title=Media:Object4&action=raw&ctype=html" style="width:100%; height:100%"></object>
Additionally, if the page that you are fetching is on the same domain, you can use AJAX to fetch it.
How would one go about embedding XML in a HTML page?
I was thinking using CDDATA would be the best approach but I get errors in the HTML document when the page loads.
<script><![CDATA[ ... ]]></script>
I'm needing to embed a XML document for fetching later with JavaScript. I need to do this since when the user opens it, they might not have internet access.
As long as the XML doesn't contain </script> anywhere, you can put it inside the script tags with a custom type attribute (and no CDATA section). Give the script tag an id attribute so you can fetch the content.
<script id="myxml" type="text/xmldata">
<x>
<y z="foo">
</y>
</x>
</script>
...
<script> alert(document.getElementById('myxml').innerHTML); </script>
http://jsfiddle.net/hJuPs/
How about:
<script>
var xml = '<element> \
<childElement attr="value" /> \
</element>';
</script>
That would enable you to easily embed the XML for later retrieval in javascript.
According to the tutorial here, you can use the 'xml' tag to embed XML data within an HTML document. However, this implicitly displays the XML data in the browser.
http://www.expertrating.com/courseware/XMLCourse/XML-Embedding-HTML-8.asp