Hongfeng Wang
Hongfeng Wang

Reputation: 13

XSLT not getting parameter passed from javascript

Very simple code, I just couldn't make it work. The parameter in XSLT is always empty. What am I missing? I am using FF6. Please help, you guys with sharp eyes. Thanks!

index.html

<html>
<head>
<script>
function loadXMLDoc(dname) {
    xhttp = new XMLHttpRequest();
    xhttp.open("GET", dname, false);
    xhttp.send("");
    return xhttp.responseXML;
}
function displayResult(source,styledoc,section) {
    xml = loadXMLDoc(source);
    xsl = loadXMLDoc(styledoc);

    if (window.ActiveXObject) {
        ex = xml.transformNode(xsl);
        document.getElementById("display").innerHTML = ex;
    }
    else if (document.implementation && document.implementation.createDocument) {
        xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsl);
        xsltProcessor.setParameter(null,"section",section);
        alert(xsltProcessor.getParameter(null,"section"));
        resultDocument = xsltProcessor.transformToFragment(xml, document);
        document.getElementById("display").appendChild(resultDocument);
    }
}
</script>
</head>
<body onload="displayResult('test.xml','test.xslt','somevalue')">
<div id="display"/>
</body>
</html>

test.xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template  match="/">
    <xsl:param name="section"/>
        section=<xsl:value-of select="$section"/>
    </xsl:template>
</xsl:stylesheet>

test.xml

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="test.xslt"?>
<test/>

Upvotes: 1

Views: 3091

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117314

setParameter() will set a global variable(parameter).

You need to move the param-element out of the template-element to make it a child of the stylesheet-element, otherwise it will override the global parameter.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="section"/>
<xsl:template  match="/">   
        section=<xsl:value-of select="$section"/>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 3

Related Questions