简体   繁体   中英

How do i pass parameters to JavaScript function via out.print in jsp?

My JavaScript function is:

function f1(name){
    alert("Hello "+name);
}

My JSP code is:

<% out.print("<button onclick='f1(Rahul)'>Click me</button>"); %>

You can use escape sequences (\\) to do such jobs! Try this:

<% out.print("<button onclick='f1(\"Rahul\")'>Click me</button>"); %>

Since Rahul is a plain String you want/need to pass it as parameter, you should escape it with quotes (") by using backslash (\\) character:

<% out.print("<button onclick='f1(\"Rahul\")'>Click me</button>"); %>
                                  ^escape the quote

Still, since you're already in JSP, you don't need to write the HTML code inside scriptlet, so you can change this to:

<%
    ...whatever code is here, probably a loop (very strange, indeed)
%>
    <button onclick='f1("Rahul")'>Click me</button>
<%
    rest of your scriptlet code...
%>

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