Search code examples
javascriptjavazk

Why can't I pass a Java String value from zscript to javascript in ZK?


Here's what I have in a zhtml file right now:

<zscript>
  String sample="123456";
</zscript>
<script>
  function called(){
    var jsample=${sample};
    alert(jsample);
  }
</script>

If sample is an int or Boolean or a String with nothing but numbers,it works fine.I call the function,alert box pops up showing the value,whether a series of numbers or true/false.

But if sample contains a character,like

String sample="q123456";

Then it stops working.I call the function,but nothing happens,it stopped at

var jsample=${sample};

I'm curious what's causing that.It felt like basic javascript though.

Many thanks.


Solution

  • Yes, it is basic JavaScript. But you have to imagine what the code looks like after ${sample}; has been resolved by the zul parser:

    var jsample=123456;   // jsample is a number, value 123456
    var jsample=false;    // jsample is a boolean, value false
    var jsample=q123456;  // jsample is something, value whatever q123456 is
    

    You can see that JavaScript thinks q123456 is a variable name, which it cannot find. It will tell you if you open the console, Chrome for example says: "Uncaught ReferenceError: asdasd is not defined".

    To solve this, change the zScript to

    var jsample="${sample}";
    

    which wraps sample into a string, so the resulting JavaScript code will look like this now:

    var jsample="123456";
    var jsample="false";
    var jsample="q123456";
    

    If you need specific types, JavaScript might automatically convert jsample, or you do it manually with checks like isNaN.