I have a html page like:
<html>
<head>
<script>
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
xml=loadXMLDoc("1.xml");
xsl=loadXMLDoc("2.xsl");
// code for IE
if (window.ActiveXObject)
{
xml.addParameter("rss", test);
ex=xml.transformNode(xsl);
document.getElementById("example").innerHTML=ex;
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
document.getElementById("example").appendChild(resultDocument);
}
}
</script>
</head>
<body onload="displayResult()">
<div id="example" />
</body>
</html>
Now I would like to pass a variable (javascript) to the XSL like for example "course_name" so that in the XSL I can use it like
<xsl:param name="course_name" />
<xsl:value-of select="$course_name" />
Any help with the approach to solve this problem is highly appreciated.
You can do it like this:
xsltProcessor.setParameter(null, "course_name", "whatever the name is");
and for IE, you will need to change your code as per http://msdn.microsoft.com/en-us/library/windows/desktop/ms762312%28v=vs.85%29.aspx , but the command is:
xslproc.addParameter("param1", "Hello");
...but given that you added "xslt-2.0" as a tag, you should know that built-in XSLT support in browsers only goes up to XSL 1.0.
The following may be of additional help:
https://developer.mozilla.org/en-US/docs/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations
https://developer.mozilla.org/en-US/docs/The_XSLT_JavaScript_Interface_in_Gecko/Setting_Parameters
http://msdn.microsoft.com/en-us/library/windows/desktop/ms762312%28v=vs.85%29.aspx
The Saxon-CE XSLT 2.0 processor runs in the browser as a JavaScript library/framework. Because its JavaScript there's a high level of interoperability, so you can pass parameters to the XSLT processor, but you can also call JavaScript functions from the XSLT, which gives added flexibility.
When passing values across, arrays in JavaScript correspond to XSLT 2.0 sequences, but some care is still required to ensure types are preserved across the language boundary.
The JavaScript API for Saxon-CE has 2 distinct forms of syntax - one is the same as that in your code, but below is an example of the alternate syntax - the same code runs on all the major browsers:
<!DOCTYPE html>
<html>
<head>
<title>stacko</title>
<script type="text/javascript" language="javascript"
src="../Saxonce/Saxonce.nocache.js"></script>
<script type="text/javascript" language="javascript">
var my_course = "physics";
onSaxonLoad = function() {
proc = Saxon.run( {
stylesheet: 'stacko.xsl',
source: 'stacko.xml',
parameters: {
course_name: my_course,
tutor: "Mr smith"
}
} );
}
</script>
</head>
<body>
<div id="example"></div>
</body>
</html>
There's no need to return the result fragment back to JavaScript with this processor (though you can if necessary), because the XSLT 2.0 xsl:result-document instruction has been extended so it can use an href attribute that specifies the id of the element in the HTML page to update, for example:
<xsl:result-document href="#example" method="replace-content">
<p><xsl:value-of select="ixsl:source()/books/book[#title = 'One']/></p>
</xsl:result-document>
There's more detail in the API section of the Saxon-CE documentation
Related
I want to create a simple script that changes LESS variables and print the CSS output in a div.
this is my HTML
<input type="text" id="choose-color" onchange="ModifyColorsInLess()">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
This is my js
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status === 200 && xmlhttp.readyState === 4){
lessCode = xmlhttp.responseText;
new(less.Parser)().parse(lessCode, function (e, tree) {
document.getElementById('lesscode').innerHTML = tree.toCSS().replace(/\n/g,"<br>");
});
}
};
xmlhttp.open("GET","css/styles.less",true);
xmlhttp.send();
}
function ModifyColorsInLess() {
less.modifyVars(
{
'#colore-body': $("#choose-color").val()
}
);
}
The script prints CSS code correctly, but if i insert a new color value in the input type="text" and call the writeCSS function, it doesn't print my variable edit.
I think the problem is that "modifyvar" does not change the file "styles.less", so when I call the function writeCSS() does not detect changes made.
is there a way to print the css dynamically detecting changes made with modifyvar?
update
When you allow the compiled styles are directly applied on your page, you can simply call `modifyVars as follows:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<link rel="stylesheet/less" type="text/css" href="t.less">
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
less.modifyVars({
'colore-body': document.getElementById('choose-color').value
});
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
Demo: http://plnkr.co/14MIt4gGCrMyXjgwCsoc
end update
Based on How to show the compiled css from a .less file in the browser?, How to update variables in .less file dynamically using AngularJS and Less: Passing option when using programmatically (via API) (you should also read: http://lesscss.org/usage/#programmatic-usage) you should be able to use the code like that shown below:
<!DOCTYPE html>
<html>
<head>
<title>Less Example</title>
<script>
less = {
env: "development"
}
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.0/less.min.js"></script>
<script>
function writeCSS(){
var lessCode = '';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
var options = {}
options['modifyVars'] = {'colore-body' : document.getElementById('choose-color').value}
lessCode = xmlhttp.responseText;
less.render(lessCode, options, function (error, output) {
if(!error) {
document.getElementById('lesscode').innerHTML = output.css;
}
else document.getElementById('lesscode').innerHTML = '<span style="color:red">' + error + '</span>';
});
}
};
xmlhttp.open("GET","styles.less",true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" id="choose-color">
<button onclick="writeCSS()">aggiorna</button>
<div id="lesscode"></div>
</body>
</html>
demo: http://plnkr.co/YbdtOwOeQPC1k9Vq4ZBv
And finally based on Force Cache-Control: no-cache in Chrome via XMLHttpRequest on F5 reload you can prevent caching of your source file with the following code:
xmlhttp.open("GET","t.less?_=" + new Date().getTime(),true);
In the above the env: "development" setting prevents your source files from caching. To clear the cache otherwise, you should call less.refresh(true) before your less.render call.
i have another little problem, if in my less file there is a reference
to another less file like this(#import "another.less") script doesn't
work.
Make sure that another.less in the above is in the same folder as your styles.less file. Notice that import (when using less in browser) are read with a XMLHttpRequest too. So your imported files should be readable by browser and their paths should be relative to the styles.less file. Also see http://lesscss.org/usage/#using-less-in-the-browser-relativeurls
Thanks all for your help!
I'm new to programing and I'm trying to show all the elements of a node based on the ID. My html doc is simple...loading the loadxmldoc.js file. I need to load all the elements including images from a folder that correspond to the player ID. What I really need a way to display character profiles based on a A-Z list.
I will probably make an xml file for each Player last name Initial...(e.g. Player_LastName_A.xml, Player_LastName_B.xml for each letter of the alphabet to load the xml faster)
If there is a simple A-Z menu script that shows all of category "A" that would be great!
My HTML:
<!DOCTYPE html>
<html>
<head>
<script src="loadxmldoc.js"></script>
</head>
<body>
<script>
xmlDoc=loadXMLDoc("Players.xml");
I want to show all player data (Name, Intro DOB etc.) based on ID=1234
</script>
</body>
My Players.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Players>
<Player ID="1234">
<Name>Adam</Name>
<Introduction>Blah Blah</Introduction>
<DOB>01/01/2000</DOB>
<Photo source="Players/3478.jpg">Players/3478.jpg</Photo>
<Resides>Sheffield</Resides>
<ProYear>2011</ProYear>
<BestRanking>2012</BestRanking>
</Player>
<player ID="1235">
<Name>Adam B</Name>
<Name>Adam</Name>
<Introduction>Blah Blah</Introduction>
<DOB>01/01/2000</DOB>
<Photo source="Players/3478.jpg">Players/3478.jpg</Photo>
<Resides>Sheffield</Resides>
<ProYear>2011</ProYear>
<BestRanking>2012</BestRanking>
</player>
</Players>
My loadxmldoc.js file:
// JavaScript Document
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
I was trying to get the text file into textarea. The result is "http://mywebsite.com/textfile/(txtinput).txt and the text file doesn't load into textarea.
<html>
<head>
<title>textbox</title>
<script type="text/javascript">
function readBOX() {
var txtinput = document.getElementById('txtinput').value;
document.forms[0].text.value = ("http://mywebsite.com/textfile/") + txtinput +(".txt");
}
</script>
</head>
<body>
<p> Type</p>
<input type="text" id="txtinput" />
<input id="open" type="button" value="READ" onClick="readBOX()" />
<form>
<textarea name="text" rows="20" cols="70">loaded text here</textarea>
</form>
</body>
</html>
You have to use something like its posted in this Answer
jQuery
$(document).ready(function() {
$("#open").click(function() {
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$("#text").text(data);
}
});
});
});
Read more on the jQuery Documentation of .ajax()
Non jQuery
I you do not want to use jQuery you have to use the XMLHttpRequest-Object something like that:
var xmlhttp, text;
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://www.example.com/file.txt', false);
xmlhttp.send();
text = xmlhttp.responseText;
But this can be read on the SO-Answer here or the complete and understandable documentation on Wikipedia
Note: But this is not cross browser compatible, for older IE version you have to use the ActiveXObject("Microsoft.XMLHTTP") object
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
This is how I load text into a textarea
Main.css
.textbox{
font-size: 12px;
float : left;
height : 197px;
width : 650px; }
Default.html
<!DOCTYPE html>
<html>
<head>
<!-- Charactor set allowed to use -->
<meta charset="utf-8"/>
<title>Text from .txt file to TextArea</title>
<!-- External stylesheet -->
<link rel="stylesheet" href="main.css" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<textarea class="textbox" id="Brief" readonly></textarea>
<script> $( "#Brief" ).load( "text.txt" ); </script>
</body>
</html>
google textarea to find format of text area
One of the easiest way is to request the server to return the pre-filled textarea
(Here's an example using PHP):
<textarea name="text" rows="20" cols="70">
<?php
echo file_get_contents('yourFile.txt');
?>
</textarea>
Note: Something similar can be done with any server-side scripting language.
In the meantime, if you need to load it dynamically, your best bet is using an AJAX approach. Choose which approach is the best for you to code and maintain. While jQuery is a popular approach, you are free to use anything you feel confortable with and probably want to know about XmlHttpRequest first.
Dynamic AJAX requests with Pure JavaScript can be tricky so make sure that your solution is cross-browser. A common mistake is using XmlHtpRequest directly and failing to make it compatible with older IE versions, which leads to random bugs depending on which browser / version you use. For example, it could look like this (would need to be tested on all targeted browser so you can add fallbacks if needed):
Pure JS:
if (typeof XMLHttpRequest === "undefined") {
XMLHttpRequest = function () {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
}
function readBOX() {
function reqListener () {
document.forms[0].text.value = this.responseText;
}
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", filePath, true);
oReq.send();
}
But if you don't mind to sacrifice some performances to ensure maximum support, you should use jQuery's implementation:
jQuery:
function readBOX() {
var txtinput = document.getElementById("txtinput").value;
var filePath = "http://mywebsite.com/textfile/" + txtinput + ".txt";
$.ajax({
url: filePath
}).done(function(data){
document.forms[0].text.value = data;
});
}
Note: jQuery's library is kind of huge, but keep in mind that if you include it directly from google servers, your user more likely has it already in cache.
Hope this helps :)
window.addEventListener('DOMContentLoaded', (e) => {
let input = document.getElementById('input');
// load default.txt into input box
try {
let fileToLoad = './default.txt';
let xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', fileToLoad, false);
xmlhttp.send();
input.innerHTML = xmlhttp.responseText;
} catch(DOMException) {
input.innerHTML = "Error loading file. Maybe related to filepath or CORS?";
}
});
First let me thank you for the assistance, I am new to Javascript, and want to learn to parse a >.xml file into my javascript. The file I want to parse is contact.xml, located in my root folder.
Again, thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
// IE 5 and IE 6
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
<title>Contacts</title>
</script>
</head>
<body>
<script type="text/javascript">
xmlDoc = loadXMLDoc("contactinfo.xml") // Path to the XML file;
var M = xmlDoc.getElementsByTagName("item");
for (i=0;i<M.length;i++){
document.write("<div style='width:450px;'>")
document.write("<h2>"+xmlDoc.getElementsByTagName("item")[i].childNodes[0].nodeValue+"</h2>");
document.write("<p>" + xmlDoc.getElementsByTagName("servicephone")[i].childNodes[0].nodeValue+ "</p>");
document.write("<p><a href='" + xmlDoc.getElementsByTagName("email")[i].childNodes[0].nodeValue +"</p>);
document.write("</div>")
}
</script>
</body>
</html>
*Here is my .xml file*
<?xml version="1.0" encoding="utf-8" ?>
<Contacts>
<item servicephone="(800) 500-0066"
email="customerservice#fsig.com"
url="http://www.fsig.com"
address="5000 Barcilona Beach Rd. Wilmington, NC 28000">
</item>
</Contacts>
You need to go down the hierarchy, so, first find the Contacts node, then inside there you can get all the tagnames as you have.
You have a great deal of attributes so you may find this useful also:
node.attributes["url"].nodeValue
So just loop through all the items, then I would just copy itemelem[t] to node just to make it easier, then you get the attributes you need.
Depending on the browser you are using most of them come with some javascript debugger, so you can put in breakpoints and look at the values in the variables and see what the next step needs to be.
i want to run xsl file using javascript function. I wrote a javascrpt function which is working well with Firefox and Crom but it is not working on Internet Explorer
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
function displayResult()
{
xml=loadXMLDoc("NewXml.xml");
xsl=loadXMLDoc("NewFile.xsl");
// code for IE
if (window.ActiveXObject)
{
ex=xml.transformNode(xsl);
document.getElementById("example").innerHTML=ex;
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
document.getElementById("example").appendChild(resultDocument);
}
}
Please help my by modifying this code or by another code so that i can work with Internet Explorer.
Thanks
To apply xsl trasformation I use, and promote, Sarissa. It is a crossbrowser library that envelope the xml apis of the different browser.
For an example of a trasformation with Sarissa you can head straight to the howto page
but it is similar to this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>sarissa test1</title>
<script type="text/javascript" src="sarissa.js"></script>
</head>
<body>
<script type="text/javascript">
function loadXMLDoc(dname) {
xhttp = new XMLHttpRequest();
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
var processor = new XSLTProcessor();
var theXML = loadXMLDoc('xml.xml');
var theXSL = loadXMLDoc('xsl.xsl');
// prepare the processor
processor.importStylesheet(theXSL);
var theResult = processor.transformToDocument(theXML);
// now you have a DomDocument with the result
// if you want to serialize (transform to a string) it you van use
document.write(new XMLSerializer().serializeToString(theResult));
</script>
</body>
</html>
Quick, easy, mantained and you can focus your efforts to the xsl creation instead than struggling to overcome the browsers differences.
The single glitch, to me is a plus but someone may see it as a limitation, the code is released under GPL 2.1 or higher or, if you prefer Apache Licence 2.0 or higher
Edit: Mine fault, I posted an old (and wrong code) without checking it. Created a new version miming your script (and tested it) on firefox, chrome, ie8, ie7 and it worked flawlessy. I used the first two xsl/xml found on a google search (I report them below for
completeness). Try the code as is and with your xsl/xml. If it goes wrong report the malfunction too (we can be more effective with a deeper error description than - don't work - ). What happens when the code misbehave? (the browser freeze, report an error, return a blank result)
xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--?xml-stylesheet type="text/xsl" href="xsl.xsl"?-->
<tutorials>
<tutorial>
<name>XML Tutorial</name>
<url>http://www.quackit.com/xml/tutorial</url>
</tutorial>
<tutorial>
<name>HTML Tutorial</name>
<url>http://www.quackit.com/html/tutorial</url>
</tutorial>
</tutorials>
xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- try to enable/disable the xsl:output -->
<!-- xsl:output method="xml"
version="1.0"
encoding="iso-8859-1"
indent="yes"/-->
<xsl:template match="/">
<html>
<head>
<title>XML XSL Example</title>
<style type="text/css">
body
{
margin:10px;
background-color:#ccff00;
font-family:verdana,helvetica,sans-serif;
}
.tutorial-name
{
display:block;
font-weight:bold;
}
.tutorial-url
{
display:block;
color:#636363;
font-size:small;
font-style:italic;
}
</style>
</head>
<body>
<h2>Cool Tutorials</h2>
<p>Hey, check out these tutorials!</p>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="tutorial">
<span class="tutorial-name"><xsl:value-of select="name"/></span>
<span class="tutorial-url"><xsl:value-of select="url"/></span>
</xsl:template>
</xsl:stylesheet>