开发者

Passing apostrophe in javascript function

I have jsp code as:

onclick="showURL('${result.url}')"

${result.url} is dynamic value. When an apostrophe comes in the URL I get the error.

I have tried all the methods like escape, encodeURI, replacing the single quotes with double but nothing works.

开发者_如何学JAVAScript call is as follows:

function showURL(name){
    alert(name);
} 


<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
${fn:escapeXml(myString)}

See: How can I escape special HTML characters in JSP?


You need to ensure that ${result.url} returns a valid URL. Quotes are invalid in URLs. It sounds like that you're returning an URL with a query string with unencoded parameters like follows

public String getUrl() {
    return "page.jsp?foo=" + foo + "&bar=" + bar;
}

You need to change the method as follows

public String getUrl() {
    return "page.jsp?foo=" + URLEncoder.encode(foo, "UTF-8") + "&bar=" + URLEncoder.encode(bar, "UTF-8");
}

You cannot fix this in the JavaScript side with escape(), etc. It's already too late then.


why not just do this:

onclick=showURL("${result.url}");

function showURL (result_url) {
    alert("<c:out value='"+ result_url + "' />");
}

then you don't have to worry about escaping at all.

-tjw

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜