简体   繁体   中英

Calling JavaScript function in Java

I'm trying to send an email using a javascript code in a Java project. Database connection works fine, I already tested it. I got the error: javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing ) after formal parameters (#1) in at line number 1

The only information of relevance is not readily reported: the final JavaScript string executed. Make sure to look at relevant data when debugging. After inspecting the final string it will be apparent why it is incorrect and trivial to "fix".

Hint: it will look something like function sendMail(userblah, foo@bar.qux) { .. , which is indeed invalid JavaScript.

The problem and solution should be self-evident from that - use fixed parameters (variable names) in the function declaration and supply arguments (values) via the invokeFunction call.


Solution:

// The following parameter names are JAVASCRIPT variable names.
String script = "function sendMail(username, email, body) { ..";

// And pass correct arguments (values), in order. The variables used
// here are JAVA variables, and align by-position with the JS parameters.
inv.invokeFunction("sendMail", username, email, "EMAIL SENT!!!!");

In addition, the getElementById (invalid ID) is wrong, the body parameter is never used, and encodeURIComponent should be used (instead of escape ).

Not sure if this is a typo or not:

    result = request.executeQuery("SELECT user.login, user.email "
                    + "FROM user " + );

It looks like you are missing the end of your statement.

Hmmmm, your function definition:

function sendMail("username","email") {...}

doesn't look like valid JavaScript to me, apart of that, you never call the function.

Pseudocode, how to do it:

function sendMail(username, email) {
    var link = "jadajada" + email; // .... etc
}
sendMail("+username+","+email+");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM